Sub topic 12
Deleting attributes with a deleter
This chapter assumes you can write a property with a getter and a setter, and that you know what del obj.attr does on a plain attribute. A deleter is the third and least used part of a property. It lets you control what happens when someone runs del obj.attr.
What `del` does by default
On a plain attribute, del obj.name removes the name from the instance's __dict__. A property is different. It lives on the class, so del has nothing to remove on the instance. Python calls the property's deleter instead.
If the property has no deleter, del fails:
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
c = Circle(2)
try:
del c.radius
except AttributeError as exc:
print("cannot delete:", exc)The property is read-only for assignment and for deletion. You don't need to write anything to get this behavior.
Writing a deleter
You register a deleter with @name.deleter, using the name of the existing property. The getter must come first, as it does with the setter.
class Profile:
def __init__(self, email):
self.email = email
@property
def email(self):
return self._email
@email.setter
def email(self, value):
if "@" not in value:
raise ValueError("email must contain @")
self._email = value
@email.deleter
def email(self):
print("clearing email")
del self._email
p = Profile("[email protected]")
print(p.email) # [email protected]
del p.email # clearing email
try:
print(p.email)
except AttributeError as exc:
print("email is gone:", exc)The deleter removes the stored value _email. The email property still exists on the class. After the deletion, the getter fails with AttributeError because self._email is missing. You can also assign to p.email again, because the setter creates _email anew.
Resetting instead of removing
A deleter does not have to remove anything. A common alternative is to reset the value to a default, so the object always stays valid.
class Settings:
DEFAULT_TIMEOUT = 30
def __init__(self):
self._timeout = self.DEFAULT_TIMEOUT
@property
def timeout(self):
return self._timeout
@timeout.setter
def timeout(self, value):
if value <= 0:
raise ValueError("timeout must be positive")
self._timeout = value
@timeout.deleter
def timeout(self):
self._timeout = self.DEFAULT_TIMEOUT
s = Settings()
s.timeout = 5
del s.timeout
print(s.timeout) # 30Here del s.timeout means "go back to the default". Document this in the docstring, because readers expect del to remove things.
Common errors
- Using a different name.
@email.deletermust match the property name. A deleter defined as a separate method namedremove_emailis just an ordinary method. - Starting with
@propertyagain. Writing@propertyabove the deleter creates a new read-only property and discards the setter. - Forgetting that the deleter runs on the instance. The deleter receives
selfand acts on that one object. It never removes the property from the class. - Deleting a value the getter needs. After
del self._email, every read raisesAttributeError. Either allow that deliberately or reset to a default.
Deleting a `cached_property`
A functools.cached_property stores its result in the instance's __dict__ under the same name. You can't use @name.deleter with it, but del obj.name still works. It removes the cached value, and the next read recomputes it.
from functools import cached_property
class Report:
def __init__(self, rows):
self.rows = rows
@cached_property
def total(self):
print("computing")
return sum(self.rows)
r = Report([1, 2, 3])
print(r.total) # computing, then 6
del r.total # clears the cached value
r.rows.append(4)
print(r.total) # computing, then 10This is the usual way to invalidate a cache.
Exercise
A class defines a property size with a getter and a setter, but no deleter. What happens when you run del obj.size, and what is the smallest change that makes the call reset _size to 0?
Show answer
Python raises AttributeError, because a property without a deleter cannot be deleted. Add a method decorated with @size.deleter that runs self._size = 0. It must come after the getter, and it must not be preceded by a new @property.