Dynamic attribute cleanup
A configuration or plugin system determines which object field to remove from a string value.
Python · Function
delattr() deletes a named attribute from an object when the object permits it. Because the name is supplied as a string, it supports attribute deletion chosen dynamically at runtime.
delattr() removes a named attribute from an object when that object permits deletion. It accepts the target object and an attribute name as a string, making it useful when the attribute name is computed at runtime; direct deletion with del is equivalent when the name is written literally.
delattr(object, name, /)| Name | Type | Description |
|---|---|---|
object | object | The object from which the attribute should be deleted. |
name | str | A string containing the name of an attribute on object. |
The documentation describes the deletion operation but does not specify a return value.
class Config:
mode = "safe"
config = Config()
assert config.mode == "safe"
delattr(config, "mode")
assert not hasattr(config, "mode")Use the attribute name as a string when removing an attribute dynamically.
A configuration or plugin system determines which object field to remove from a string value.
Code must remove an attribute whose spelling is not known until runtime.
A generic object-management utility needs the function form corresponding to setattr().
delattr() takes an object and a string naming one of its attributes, then deletes that attribute if the object permits it. It is the dynamic equivalent of deleting an attribute with del when the name is known in source code.
Follow-up: What must you do when the attribute name is computed at runtime? Pass the computed string to delattr(); direct dotted syntax cannot substitute a variable for the attribute name.
The first argument is the object whose attribute is targeted, and the second is the attribute name as a string. Both arguments are positional-only in the documented signature.
Follow-up: Why is the name a string rather than an expression? Because delattr() needs the attribute's textual name, including names selected dynamically.
For a literal attribute name, delattr(x, 'foobar') has the same effect as del x.foobar. The function form is useful when the name is supplied or calculated as data.
Follow-up: Can every object have an attribute deleted? No; deletion occurs only if the object allows it, so the object's attribute implementation determines whether it succeeds.
setattr()del