Python 3 reference · Built-in Functions
Python delattr() Function
Delete a named attribute from an object. delattr(obj, 'name') does the same as del obj.name when the name is in a variable.
Python 3 Since 3.0
Syntax
delattr(object, name)
Parameters
| Parameter | Description |
|---|---|
object |
The object to change. |
name |
The attribute name, as a string. |
Return value
None.
Examples
class Config:
pass
c = Config()
c.debug = True
delattr(c, "debug")
print(hasattr(c, "debug"))
Output
False
class User:
pass
u = User()
u.name, u.password, u.email = "ada", "secret", "[email protected]"
for field in ["password"]:
delattr(u, field)
print(vars(u))
Output
{'name': 'ada', 'email': '[email protected]'}Good to know
Deleting a missing attribute raises AttributeError. Use if hasattr(obj, name): first if it might not exist.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
getattr()· Get an attribute by name, given as a string. An optional default is returned instead of raising AttributeError.setattr()· Set an attribute on an object by name, given as a string. setattr(obj, 'x', 5) is the same as obj.x = 5.hasattr()· Return True if an object has an attribute with the given name. It works by calling getattr() and catching AttributeError.vars()· Return the __dict__ of a module, class or object: its writable attributes as a dictionary. With no argument, like locals().- Python Classes and Objects · tutorial