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.
delattr(user, "temp_token") # same as: del user.temp_token
Try it
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.
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
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. Usedel obj.attrwhen the name is fixed in the code, anddelattr()when it is a variable. - Own attributes only.
delattr(instance, "x")removesxfrom the instance. If the value comes from the class, you must delete it on the class. - Missing names fail. Check with
hasattr()first, or catchAttributeError; there is no default argument likegetattr()has. - Hooks. A class can customize deletion with
__delattr__(). Descriptors such as properties can define__delete__()(or adeleter). - 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"]ord.pop("key");delattr()has no effect on keys.
Related
getattr(),setattr(),hasattr(),vars(),property()- Lessons: Classes, Properties, Special methods