Sub topic 12
Deleting attributes with a deleter
This chapter assumes you can write a class with __init__, and that you know @property getters and setters from the earlier chapters. You should also be comfortable with try/except. Here you will learn what del obj.attr does when attr is a property, how to write a deleter, and where deleters are useful.
What `del` does on an attribute
The statement del obj.name removes an attribute. For a plain instance attribute, Python removes the name from the instance's __dict__. Any later read raises AttributeError.
A property changes this. The property object lives on the class and intercepts del the same way it intercepts reads and writes. The three operations map to three functions stored in the property:
| Operation | Function in the property | Without that function |
|---|---|---|
| `obj.x` | `fget` (the getter) | `AttributeError` |
| `obj.x = v` | `fset` (the setter) | `AttributeError` |
| `del obj.x` | `fdel` (the deleter) | `AttributeError` |
A property with only a getter is read-only, and it is also non-deletable. Calling del on it raises AttributeError.
class Tag:
def __init__(self, label):
self._label = label
@property
def label(self):
return self._label
t = Tag("python")
try:
del t.label
except AttributeError:
print("label cannot be deleted") # no deleter was defined
print(t.label) # pythonThe object is unchanged after the failed del. Python found the property and looked for fdel. It found none, so it raised the error.
Writing a deleter
You add a deleter with @name.deleter, where name is the property you already defined. The decorated function takes only self, and its return value is ignored.
The example below has a nickname that falls back to the user's name. Deleting the nickname resets it to the fallback.
class User:
def __init__(self, name, nickname=None):
self.name = name
self._nickname = nickname
@property
def nickname(self):
if self._nickname is None:
return self.name
return self._nickname
@nickname.setter
def nickname(self, value):
self._nickname = value.strip()
@nickname.deleter
def nickname(self):
self._nickname = None
u = User("Ada Lovelace")
print(u.nickname) # Ada Lovelace
u.nickname = " Ada "
print(u.nickname) # Ada
del u.nickname
print(u.nickname) # Ada Lovelace
del u.nickname # fine: the deleter is safe to run twiceThe deleter does not remove the property. It runs your code, and here that code sets _nickname back to None. The nickname property still exists on the class and keeps working. That is the main difference from deleting a plain attribute.
The three functions share one name. Each decorator (@nickname.setter, @nickname.deleter) returns a new property object that copies the existing functions and adds one. Python then rebinds the name nickname in the class body to that new object. This is why every function in the group must use the same name.
Three common deleter designs
The body of a deleter is ordinary code, so it can do different jobs. Three designs come up often.
Remove the backing attribute
The most literal deleter deletes the private attribute behind the property:
class Note:
def __init__(self, text):
self._text = text
@property
def text(self):
return self._text
@text.deleter
def text(self):
del self._text
n = Note("remember the milk")
del n.text
print(hasattr(n, "text")) # False
try:
del n.text
except AttributeError:
print("already deleted")After the first del, _text no longer exists. The getter then fails with AttributeError when it reads self._text. hasattr catches that error and reports False, so the attribute looks absent. A second del fails for the same reason. Python itself raises the error from del self._text, and you did not write any code for it.
This design is honest, because the attribute behaves as if it were gone. It is also fragile. Code that reads the property later gets an error from inside the getter, and the traceback points at the private name.
Reset to a default
The User example above takes the other approach: the deleter restores a default and the property stays usable. Choose this when "no value" is a normal, valid state.
Release a resource
A deleter is a natural place to clean up something the property created lazily:
class FakeConnection:
def close(self):
print("connection closed")
class Session:
def __init__(self):
self._connection = None
@property
def connection(self):
if self._connection is None:
print("opening connection")
self._connection = FakeConnection()
return self._connection
@connection.deleter
def connection(self):
if self._connection is not None:
self._connection.close()
self._connection = None
s = Session()
s.connection # opening connection
del s.connection # connection closed
del s.connection # does nothing: already closed
s.connection # opening connection (a new one)The if guard makes the deleter idempotent: running it again has no effect. Idempotent deleters are easier to use, because callers do not need to track whether the resource is open.
A common mistake: a different function name
Because each decorator rebinds a name, a deleter with a different function name does not attach to the original property. This code looks right but fails:
class Broken:
def __init__(self):
self._x = 1
@property
def x(self):
return self._x
@x.deleter
def remove_x(self): # wrong name: should be x
del self._x
b = Broken()
try:
del b.x
except AttributeError:
print("x still has no deleter")
del b.remove_x # works, but only by accident
print(hasattr(b, "_x")) # False@x.deleter builds a new property with both the getter and the deleter, and the class stores it as remove_x. The original x is unchanged, so it has no deleter. The class now has two properties, and only the oddly named one can delete. Always repeat the property name exactly.
Deleting a `cached_property`
functools.cached_property stores its computed value in the instance's __dict__. It is not a data descriptor, which means there is no fdel to define. Deleting the cached value is a normal del on the instance's __dict__ entry, and it is the standard way to invalidate the cache:
from functools import cached_property
class Dataset:
def __init__(self, values):
self.values = values
@cached_property
def total(self):
print("computing")
return sum(self.values)
d = Dataset([1, 2, 3])
print(d.total) # computing, then 6
d.values.append(4)
print(d.total) # 6 (stale, still cached)
del d.total # removes the cached value
print(d.total) # computing, then 10
del d.total
try:
del d.total # nothing cached now
except AttributeError:
print("nothing to invalidate")If the value has not been computed yet, del d.total raises AttributeError, because there is no entry in __dict__ to remove. When you want invalidation to be safe either way, use d.__dict__.pop("total", None).
Deleters and inheritance
A property is a single class attribute. A subclass that redefines only @x.setter with @Base.x.setter gets a new property that copies the parent's getter and deleter. A subclass that writes a fresh @property def x replaces the whole property, including any deleter the parent defined. After that, del obj.x on a subclass instance fails unless the subclass defines its own deleter. The next chapters cover overriding in more detail, but remember this rule when you test deletion on subclasses.
When to write a deleter
Most properties never need one. A deleter makes sense when "removing" the value has a clear meaning for your class: resetting to a default, releasing a resource, or invalidating something derived. If deleting would leave the object in an invalid state, leave the deleter out. Python then raises AttributeError, which is a useful signal.
| Situation | Choice |
|---|---|
| Value must always exist | No deleter |
| Optional value with a default | Deleter that resets |
| Lazily created resource | Idempotent deleter that releases it |
| Computed value held in `cached_property` | Plain `del`, no code needed |
Exercise
A class defines @property def level(self) and @level.setter, but no deleter. What happens on del obj.level, and what is the smallest change that makes del obj.level reset the level to 1, assuming the value is stored in self._level?
Show answer
del obj.level raises AttributeError, because the property has no fdel. Add a deleter with the same name: @level.deleter followed by def level(self): self._level = 1. The property stays on the class, so reading obj.level afterwards returns 1.
Exercise
Given this class, why does del c.size still raise AttributeError, and how do you fix it?
class Crate:
def _init(self):
self.size = 3
@property
def size(self):
return self.size
@size.deleter
def clearsize(self):
self._size = 0
Show answer
The deleter function is named clear_size, not size. @size.deleter creates a new property and binds it to clear_size, so the size property is unchanged and has no deleter. Rename the function to size so the deleter attaches to the property that the class keeps under that name.