Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python delattr() function

Reference for Python delattr(): delete an attribute by its name given as a string, how it relates to the del statement, AttributeError and __delattr__.

The built-in delattr() function removes an attribute from an object, where the attribute name is given as a string. delattr(obj, "x") does the same as the statement del obj.x, but works when the name is only known at run time.

It pairs with getattr(), setattr() and hasattr() for code that handles attributes dynamically: configuration objects, serializers and plugin systems.

Python
delattr(user, "temp_token")   # same as: del user.temp_token

Try it

Python Removing attributes by name

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Instance vs class attributes, and __delattr__

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
delattr(object, name)
Name Description
object The object to change.
name A str giving the attribute name.

Return value: None.

Raises: AttributeError if the attribute does not exist (or the object does not allow deletion, for example one using __slots__ without that slot set, or a built-in type). TypeError if name is not a string.

Usage notes

  • Equivalent to del. Use del obj.attr when the name is fixed in the code, and delattr() when it is a variable.
  • Own attributes only. delattr(instance, "x") removes x from the instance. If the value comes from the class, you must delete it on the class.
  • Missing names fail. Check with hasattr() first, or catch AttributeError; there is no default argument like getattr() has.
  • Hooks. A class can customize deletion with __delattr__(). Descriptors such as properties can define __delete__() (or a deleter).
  • Built-in types don't allow it: delattr(int, "real") fails, as do most extension types.
  • Does not free memory directly. It removes one reference; the value is collected when no references remain.
  • Dictionary keys are different. For dictionaries use del d["key"] or d.pop("key"); delattr() has no effect on keys.