Python __delattr__ Method
Last modified November 17, 2026 Python 3.15
The del statement removes a name, an item, or an attribute, and the
attribute form is handled by __delattr__. A class can override the
method to log removals, protect required fields, or forward the deletion to
another store. This article shows the dispatch path, the interaction with data
descriptors and __slots__, and the cases where the hook is not
called at all.
How del removes an attribute
del obj.name and delattr(obj, "name") are equivalent:
both call type(obj).__delattr__(obj, "name"). The default
implementation removes the entry from the instance dictionary, and a subclass
can run code before or after delegating to super().__delattr__().
class Settings:
def __init__(self, **values):
self.__dict__.update(values)
def __delattr__(self, name):
print(f"deleting {name}")
super().__delattr__(name)
def __repr__(self):
return f"Settings({self.__dict__})"
s = Settings(debug=True, retries=3)
print(s)
del s.debug
print(s)
delattr(s, "retries")
print(s)
Both spellings reach the same method, and the dictionary shrinks after each
call. Delegating with super() keeps the standard behaviour,
including the AttributeError raised for a name that does not exist.
Removing the super() call would leave the object unchanged while
still printing the message, which is rarely what a logger wants.
$ python basic_delattr.py
Settings({'debug': True, 'retries': 3})
deleting debug
Settings({'retries': 3})
deleting retries
Settings({})
Protecting required attributes
A common use of __delattr__ is to reject deletion of fields that
the object needs in order to stay valid. The check runs before the default
implementation, so the attribute is still present when the error is raised. An
attempt to delete a name that never existed falls through to the normal
AttributeError.
class Account:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def __delattr__(self, name):
if name in {"owner", "balance"}:
raise AttributeError(f"{name} is required")
super().__delattr__(name)
def __repr__(self):
return f"Account({self.owner!r}, {self.balance!r})"
account = Account("Alice", 100)
account.note = "temporary"
print(account)
del account.note
print(account)
for name in ("owner", "missing"):
try:
delattr(account, name)
except AttributeError as e:
print(type(e).__name__, e)
The temporary note disappears, while the owner and balance are protected by a
custom message. The missing name produces the interpreter's standard message,
which names the class and the attribute. Raising AttributeError is
important here: other code, including hasattr() and the
delattr() built-in, expects that exception type for a failed
deletion.
$ python readonly.py
Account('Alice', 100)
Account('Alice', 100)
AttributeError owner is required
AttributeError 'Account' object has no attribute 'missing'
Descriptors and the deletion order
When the attribute is a data descriptor on the class, the default
__delattr__ does not remove anything from the instance dictionary.
It finds the descriptor and calls its __delete__ method. An
overridden __delattr__ runs first, so it can log or veto the
operation before the descriptor is involved.
class Field:
def __set_name__(self, owner, name):
self.name = name
def __get__(self, obj, objtype=None):
if obj is None:
return self
return obj.__dict__.get(self.name, 0)
def __set__(self, obj, value):
print(f"setting {self.name} to {value}")
obj.__dict__[self.name] = value
def __delete__(self, obj):
print(f"descriptor deleting {self.name}")
obj.__dict__.pop(self.name, None)
class Model:
score = Field()
def __delattr__(self, name):
print(f"__delattr__ called for {name}")
super().__delattr__(name)
m = Model()
m.score = 10
print(m.score)
del m.score
print(m.score)
The output shows the order: the class hook, then the descriptor's
__delete__. After the deletion, reading m.score calls
__get__ again and returns the default 0. This layering lets a class
audit every removal while each descriptor decides what deleting its value
actually means.
$ python descriptor.py setting score to 10 10 __delattr__ called for score descriptor deleting score 0
Objects with __slots__
A class with __slots__ has no instance dictionary; its attributes
are stored in fixed slots. The default __delattr__ clears a slot,
and a subclass hook can log the operation in the same way. Deleting a slot that
is already empty raises AttributeError.
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
def __delattr__(self, name):
print(f"removing slot {name}")
super().__delattr__(name)
p = Point(1, 2)
del p.x
print(p.y)
try:
print(p.x)
except AttributeError as e:
print(type(e).__name__, e)
try:
del p.x
except AttributeError as e:
print(type(e).__name__, e)
Deleting x leaves y intact, and reading the removed
slot fails with the usual message. The second deletion reaches the hook again,
but the base implementation finds no value and raises AttributeError
with the slot name alone. A hook that logs before delegating will therefore
record attempts that do not succeed.
$ python slots_attrs.py removing slot x 2 AttributeError 'Point' object has no attribute 'x' removing slot x AttributeError x
Bypassing the hook
__delattr__ is only consulted for the attribute deletion syntax.
Removing an entry from __dict__ directly, or calling
object.__delattr__() explicitly, skips the override. This is useful
to know when debugging a class whose logging does not fire, and it is a reminder
that the hook is not a security boundary.
class Tracked:
def __delattr__(self, name):
print(f"hook: {name}")
super().__delattr__(name)
t = Tracked()
t.x = 1
t.y = 2
del t.__dict__["x"]
print("after dict deletion")
object.__delattr__(t, "y")
print("after object.__delattr__")
print(t.__dict__)
Neither removal prints the hook message, and the final dictionary is empty. Code
that needs to guarantee an invariant cannot rely on __delattr__
alone; it must also control how the dictionary is exposed or validate the
object before use.
$ python bypass.py
after dict deletion
after object.__delattr__
{}
Best practices
Deletion is an operation like any other, so make its rules explicit:
- Call
super().__delattr__(name)to keep the standard__dict__and descriptor behaviour. - Raise
AttributeError, notValueErrororTypeError, when a deletion is not allowed. - Keep the hook idempotent in spirit: a repeated deletion of a missing attribute should fail consistently, not corrupt the object.
- Remember that data descriptors handle their own removal through
__delete__; do not assume the value lives in__dict__. - Handle
__slots__classes separately when writing generic attribute-management code. - Do not use
__delattr__as a security check; direct dictionary access bypasses it.
Source
object.__delattr__ - Python documentation
delattr() - Python documentation
Implementing descriptors - Python documentation
In this article we have implemented the __delattr__ method. We have
covered the del dispatch, protected attributes, descriptor
deletion, __slots__, and the paths that bypass the hook. For
related topics, see Python __getattr__ method,
Python __setattr__ method,
Python __delete__ method, and
Python __get__ method.
Author
List all Python tutorials.