Sub topic 15
Pitfalls and debugging tips
This chapter assumes you know the lookup order from the earlier chapters: a data descriptor on the class wins, then the instance __dict__, then a non-data descriptor or plain class attribute, then __getattr__. It also assumes you can write a descriptor with __get__, __set__ and __set_name__.
Pitfall 1: state stored on the descriptor
A descriptor object lives on the class, so every instance shares it. Storing a value on self therefore shares that value across all instances.
class Shared:
def __get__(self, obj, objtype=None):
return getattr(self, "value", None)
def __set__(self, obj, value):
self.value = value
class Box:
size = Shared()
a, b = Box(), Box()
a.size = 1
b.size = 2
print(a.size) # 2, not 1The fix is to store the value on the instance under a private name, as the Positive descriptor did with __set_name__.
Pitfall 2: recursion and the wrong storage name
If __set__ calls setattr(obj, "price", value) using the descriptor's own public name, the call re-enters __set__ and raises RecursionError. Store under a different name, such as "_price". You can also write directly to obj.__dict__["price"]. That works for a data descriptor, because the data descriptor takes precedence over the instance entry.
Pitfall 3: forgetting access from the class
Item.price calls __get__(None, Item). If your __get__ assumes obj is an instance, it fails with an AttributeError or TypeError on class access. This also breaks tools such as help() and documentation generators. Return self when obj is None.
Pitfall 4: expecting the wrong precedence
A descriptor that defines only __get__ is a non-data descriptor. An entry in the instance __dict__ shadows it. If you want assignment to be controlled, define __set__. If you only want read-only behavior, define __set__ and make it raise AttributeError.
Pitfall 5: descriptors in the wrong place
| Situation | What happens |
|---|---|
| Descriptor assigned to an instance (`obj.d = Desc()`) | It is just a value. `__get__` is never called. |
| Descriptor added to the class after creation (`A.d = Desc()`) | `__get__` and `__set__` work, but `__set_name__` is not called. |
| Descriptor defined in a base class | It is found through the MRO, and `__set_name__` receives the base class as `owner`. |
For the second case, call desc.__set_name__(A, "d") yourself.
Debugging an attribute
When a value is not what you expect, check each stage of the lookup separately.
import inspect
def explain(obj, name):
for base in type(obj).__mro__:
if name in vars(base):
kind = type(vars(base)[name]).__name__
print(f"class attribute on {base.__name__}: {kind}")
break
else:
print("no class attribute")
print("in instance __dict__:", name in getattr(obj, "__dict__", {}))
print("static lookup:", inspect.getattr_static(obj, name, "<missing>"))
class T:
@property
def x(self):
return 1
explain(T(), "x")inspect.getattr_static finds the attribute without running any descriptor or __getattr__, so you see the raw object. Compare it with getattr(obj, name) to see what __get__ changed.
Exercise
A descriptor defines only __get__. You run obj.__dict__["field"] = 5 and then read obj.field. Which value do you get, and what one change to the descriptor would make the descriptor win?
Show answer
You get 5, because a non-data descriptor is shadowed by the instance __dict__. Adding a __set__ method makes it a data descriptor, so its __get__ is used instead.