Sub topic 15
Pitfalls and debugging tips
This chapter assumes you have read the earlier chapters on the lookup order, data and non-data descriptors, __set_name__, and property. It collects the mistakes that come up most often when you write or use descriptors, and the tools for finding out why an attribute behaves the way it does.
Pitfall 1: Keeping per-instance state on the descriptor
A descriptor object lives on the class, so there is exactly one of it, shared by every instance. Anything you store with self.something inside the descriptor is shared too.
class Broken:
def __init__(self):
self.value = None
def __get__(self, obj, objtype=None):
return self.value
def __set__(self, obj, value):
self.value = value
class Account:
balance = Broken()
a = Account()
b = Account()
a.balance = 100
b.balance = 5
print(a.balance) # 5, not 100The fix is to store the value on the instance. Because a data descriptor wins over the instance __dict__, the descriptor can safely keep its value in the instance __dict__ under its own attribute name.
class Field:
def __set_name__(self, owner, name):
self.name = name
def __get__(self, obj, objtype=None):
if obj is None:
return self
try:
return obj.__dict__[self.name]
except KeyError:
raise AttributeError(self.name) from None
def __set__(self, obj, value):
obj.__dict__[self.name] = value
class Account2:
balance = Field()
a = Account2()
b = Account2()
a.balance = 100
b.balance = 5
print(a.balance, b.balance) # 100 5Writing obj.__dict__[self.name] is deliberate. If __set__ called setattr(obj, self.name, value) with the same name as the descriptor, that call would run __set__ again and raise RecursionError.
A common alternative is a dictionary on the descriptor keyed by instance. It forces instances to be hashable, compares them by equality, and keeps them alive forever unless you use weakref.WeakKeyDictionary. Storing on the instance avoids all three problems.
Pitfall 2: Forgetting the class-access case
When you write Account2.balance, Python still calls __get__, with obj set to None. If your __get__ assumes an instance, class access fails. Tools such as help(), inspect, documentation generators and your own debugging all access the attribute on the class. Return self when obj is None, as the examples above do.
Pitfall 3: Descriptors added after class creation
__set_name__ is called by type.__new__ while the class is being built. If you attach a descriptor later, nobody calls it.
class Positive:
def __set_name__(self, owner, name):
self.private_name = "_" + name
def __get__(self, obj, objtype=None):
if obj is None:
return self
return getattr(obj, self.private_name)
def __set__(self, obj, value):
if value <= 0:
raise ValueError("must be positive")
setattr(obj, self.private_name, value)
class Box:
pass
Box.width = Positive()
b = Box()
try:
b.width = 3
except AttributeError as e:
print(e) # 'Positive' object has no attribute 'private_name'
Box.width.__set_name__(Box, "width")
b.width = 3
print(b.width) # 3Calling __set_name__ yourself is the fix. A related trap is reusing one descriptor object under two names in the same class. __set_name__ runs twice, the second call overwrites the first, and both names then share one storage slot.
Pitfall 4: `__getattr__` hides errors raised inside properties
If __getattribute__ raises AttributeError, Python discards it and calls __getattr__. This includes an AttributeError raised from inside a property getter. The original traceback is lost.
class Report:
@property
def total(self):
return self.data["total"] # self.data was never set
def __getattr__(self, name):
raise AttributeError(f"Report has no attribute {name!r}")
try:
Report().total
except AttributeError as e:
print(e) # Report has no attribute 'total'The message blames total, but the real problem is the missing data. To debug this, call the getter directly, for example Report.total.fget(Report()). That raises the real error with its own traceback.
Pitfall 5: Expecting descriptors to work anywhere
Descriptors are only looked at when they are found on the type. The following cases surprise people:
- A descriptor stored in an instance
__dict__is returned as a plain object, and its__get__never runs. Item.price = -5replaces the descriptor on the class.type.__setattr__does not call the descriptor's__set__for class-level assignment, so validation is bypassed.- A non-data descriptor is shadowed by an instance attribute of the same name. This is the intended trick behind
cached_property, but it is a bug if you wanted a read-only attribute.
Pitfall 6: Interactions with `__slots__`
Classes with __slots__ have no instance __dict__ unless you list "__dict__" in the slots. Descriptors that store into obj.__dict__ then fail with AttributeError. functools.cached_property raises a TypeError for the same reason, since it needs somewhere to cache the value. Either add "__dict__" to the slots, or store the value in another declared slot.
Quick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| All instances show the same value | State kept on the descriptor with `self.x` | Store on the instance |
| `RecursionError` in `__set__` | `setattr(obj, name, v)` with the descriptor's own name | Write to `obj.__dict__[name]` or use a private name |
| `AttributeError` on `Cls.attr` | `__get__` does not handle `obj is None` | Return `self` |
| Private name missing | Descriptor added after class creation | Call `__set_name__` manually |
| Misleading "no attribute" error | `__getattr__` replaced an `AttributeError` from a getter | Call `fget` directly |
| Validation skipped | Assignment on the class, or a non-data descriptor | Assign on instances, or add `__set__` |
| `TypeError` from `cached_property` | Class uses `__slots__` without `__dict__` | Add `"__dict__"` to the slots |
Debugging tools
The most useful rule is to look at the attribute without triggering it. A normal getattr can run arbitrary code, which is a poor idea when the code is the thing you are debugging.
inspect.getattr_static(obj, name)follows the lookup rules without calling__get__,__getattr__or any property getter.type(obj).__mro__shows the order in which classes are searched.vars(obj)shows the instance__dict__andvars(cls)shows a class namespace. Neither shows inherited names.object.__getattribute__(obj, name)runs the standard lookup but skips a custom__getattr__, which separates "lookup failed" from "fallback ran".
You can combine these in a small helper that reports what kind of object sits on the type and whether the instance shadows it.
from functools import cached_property
def explain(obj, name):
cls = type(obj)
for base in cls.__mro__:
if name in vars(base):
attr = vars(base)[name]
t = type(attr)
if hasattr(t, "__set__") or hasattr(t, "__delete__"):
kind = "data descriptor"
elif hasattr(t, "__get__"):
kind = "non-data descriptor"
else:
kind = "plain class attribute"
print(f"{name!r}: {kind} {t.__name__} found on {base.__name__}")
break
else:
print(f"{name!r}: not on the type")
if name in getattr(obj, "__dict__", {}):
print(f"{name!r}: also in instance __dict__")
class Base:
@property
def size(self):
return 1
class Child(Base):
@cached_property
def label(self):
return "x"
c = Child()
c.label
explain(c, "size")
explain(c, "label")
explain(c, "missing")This prints:
'size': data descriptor property found on Base
'label': non-data descriptor cached_property found on Child
'label': also in instance __dict__
'missing': not on the typeThe helper leaves out two things. It does not check metaclass attributes, which matter for lookups on classes. It also does not handle the C-level special cases that inspect.getattr_static covers.
Checklist for writing a descriptor
- Define
__set_name__so the descriptor knows its attribute name. - Handle
obj is Nonein__get__. - Keep per-instance values on the instance, never on
self. - Decide on purpose whether the descriptor is data or non-data, and define
__set__only when you want it to win over the instance__dict__. - Raise
AttributeErrorfrom__get__only when the attribute is really missing, because__getattr__may swallow it.
Exercise
A descriptor defines only _get and returns obj.dict["x"]. After running obj.x = 5, the descriptor's get_ is never called again for obj.x. Why?
Show answer
With only _get, the descriptor is a non-data descriptor. The assignment obj.x = 5 does not call it. It writes 5 into the instance dict, and on lookup the instance dict takes precedence over a non-data descriptor, so 5 is returned directly. Adding set_ makes it a data descriptor, so it wins again.
Exercise
A data descriptor assigned to the class attribute total has __set__ that runs setattr(obj, "total", value). What happens when you run obj.total = 1, and how do you fix it?
Show answer
The setattr call looks up total on the type, finds the same data descriptor, and calls its _set again, which repeats forever and raises RecursionError. Fix it by writing to obj.dict["total"] directly, or by storing under a different private name such as "total".