Sub topic 5
Data and non-data descriptors
This chapter assumes you know how instance and class __dict__ namespaces work, how the MRO is searched, and that obj.name goes through object.__getattribute__. It also assumes you know the three descriptor methods: __get__, __set__ and __delete__. Here you will learn the one rule that decides whether a descriptor beats an instance attribute of the same name.
The definition
Python splits descriptors into two kinds. The split depends only on which methods the descriptor's class defines.
| Kind | Methods defined on the descriptor's class | Wins over instance `__dict__` on read? |
|---|---|---|
| Non-data descriptor | `__get__` only | No. The instance entry shadows it. |
| Data descriptor | `__set__` or `__delete__` (usually with `__get__`) | Yes. It always runs first. |
The check looks at the type of the object found on the class, not at the object itself. Python never asks "does this instance have a __set__ attribute?" It asks "does type(attr) define __set__ or __delete__?" This matches the lookup you saw in the previous chapter, where methods are found through the class and not through the instance.
Seeing the difference
The example below puts an entry in the instance __dict__ under the same name as each descriptor.
class DataDesc:
def __get__(self, obj, objtype=None):
return "data descriptor"
def __set__(self, obj, value):
print("__set__ called")
class NonDataDesc:
def __get__(self, obj, objtype=None):
return "non-data descriptor"
class A:
d = DataDesc()
n = NonDataDesc()
a = A()
a.__dict__["d"] = "instance d"
a.__dict__["n"] = "instance n"
print(a.d) # data descriptor
print(a.n) # instance nFor a.d, the lookup finds DataDesc on the class, sees that its type defines __set__, and calls __get__ immediately. The "instance d" entry is never read. For a.n, the type defines only __get__, so Python checks the instance __dict__ first and finds "instance n".
Assignment and deletion follow the same split
The rule also applies when you write to the attribute, not only when you read it.
class Logged:
def __get__(self, obj, objtype=None):
return "from descriptor"
def __set__(self, obj, value):
print(f"__set__({value!r})")
class Plain:
def __get__(self, obj, objtype=None):
return "from descriptor"
class B:
logged = Logged()
plain = Plain()
b = B()
b.logged = 1 # __set__(1)
b.plain = 2 # stored in the instance __dict__
print(b.logged) # from descriptor
print(b.plain) # 2
print(b.__dict__) # {'plain': 2}
del b.plain
print(b.plain) # from descriptorAssigning to b.logged calls Logged.__set__, so nothing lands in b.__dict__. Assigning to b.plain does what it does for any ordinary attribute and writes into the instance __dict__. After del b.plain, the shadow is gone and the non-data descriptor shows through again.
Deletion works the same way. del b.logged would call Logged.__delete__. Because Logged does not define it, Python raises AttributeError. A descriptor that defines only __delete__ still counts as a data descriptor.
Why Python draws the line here
The two kinds serve different jobs.
- A data descriptor controls the whole attribute. Reads, writes and deletes all go through it, so it can validate, compute or forbid changes.
propertyand__slots__need this guarantee. - A non-data descriptor supplies a default that an instance may override. Functions work this way, so
obj.method = something_elsereplaces a method on one instance without touching the class.
functools.cached_property relies on the same shadowing. Its first access computes a value and stores it in the instance __dict__ under the same name. Later reads find that entry first, so the descriptor is skipped.
flowchart TDThe diagram below summarizes the decision in order.
Classifying real attributes
You can classify any class attribute with a small helper. It follows the same test the interpreter uses and looks at the type, not at the instance.
import functools
def kind(cls, name):
for base in cls.__mro__:
if name in vars(base):
attr_type = type(vars(base)[name])
if hasattr(attr_type, "__set__") or hasattr(attr_type, "__delete__"):
return "data descriptor"
if hasattr(attr_type, "__get__"):
return "non-data descriptor"
return "plain attribute"
return "missing"
class Demo:
__slots__ = ("slot",)
limit = 10
@property
def prop(self):
return 1
@classmethod
def make(cls):
return cls()
def method(self):
return 2
for name in ("prop", "slot", "method", "make", "limit", "nope"):
print(name, "->", kind(Demo, name))Running it prints:
prop -> data descriptor
slot -> data descriptor
method -> non-data descriptor
make -> non-data descriptor
limit -> plain attribute
nope -> missingproperty defines __set__ even when you give it no setter. The __set__ raises AttributeError in that case, which is how read-only properties work. A __slots__ entry is a member_descriptor with __set__ and __delete__. Functions and classmethod objects define only __get__.
Adding functools.cached_property to Demo would put it in the non-data group too, which is why the cache can shadow it.
Edge cases
A descriptor with only `__set__`
The "data" test looks at __set__ and __delete__, but a data descriptor must also have __get__ to take over reads. If a class defines __set__ and no __get__, assignment is intercepted but reading falls through to the instance __dict__.
class SetOnly:
def __set__(self, obj, value):
print("set", value)
class E:
s = SetOnly()
e = E()
print(type(e.s).__name__) # SetOnly (the descriptor itself)
e.__dict__["s"] = "in dict"
print(e.s) # in dictBefore the dictionary entry exists, e.s returns the descriptor object itself, because it has no __get__ to call. Define all the methods you intend to support.
Descriptors in the instance `__dict__` are inert
Python looks for descriptors on the type only. If you store a descriptor object in obj.__dict__, reading the attribute returns that object unchanged and never calls its __get__. Descriptors must be class attributes.
Shadowing is invisible to the class
Writing to b.plain changes one instance. B.plain still returns the descriptor. A non-data descriptor therefore never receives a notification that an instance overrode it.
Order within the MRO
Python takes the first match on the MRO when deciding whether the attribute is a data descriptor. A data descriptor in a base class is hidden if a subclass defines a plain attribute of the same name earlier in the MRO. The subclass entry is the one whose type gets tested.
A model of the rule in code
The simplified lookup from the earlier chapter reduces to the same three branches. This version isolates the data/non-data decision.
_missing = object()
def find_in_mro(cls, name):
for base in cls.__mro__:
if name in vars(base):
return vars(base)[name]
return _missing
def lookup(obj, name):
cls = type(obj)
attr = find_in_mro(cls, name)
attr_type = type(attr)
is_data = (
attr is not _missing
and hasattr(attr_type, "__get__")
and (hasattr(attr_type, "__set__") or hasattr(attr_type, "__delete__"))
)
if is_data:
return attr_type.__get__(attr, obj, cls)
instance_dict = getattr(obj, "__dict__", {})
if name in instance_dict:
return instance_dict[name]
if attr is not _missing:
if hasattr(attr_type, "__get__"):
return attr_type.__get__(attr, obj, cls)
return attr
raise AttributeError(f"{cls.__name__!r} object has no attribute {name!r}")The is_data line is where this chapter's rule lives. Everything after it handles the non-data and plain cases in the usual order: instance, then class.
Exercise
A class defines x = Descr(), where Descr has __get__ and __delete__ but no __set__. After obj.__dict__["x"] = 5, what does obj.x return, and does obj.x = 7 write to obj.__dict__?
Show answer
obj.x calls Descr.__get__, because defining __delete__ makes Descr a data descriptor, so the 5 in the instance __dict__ is ignored. obj.x = 7 does not write to obj.__dict__. Python takes the descriptor's assignment path, and since Descr has no __set__, it raises AttributeError.
Exercise
Why can you replace a method on a single instance with obj.greet = lambda: "hey", but obj.celsius = 30 fails on a read-only property?
Show answer
Functions are non-data descriptors, so assignment stores the lambda in the instance __dict__, and reads find it before the class function. A property is a data descriptor whose __set__ raises AttributeError when there is no setter, so the assignment is intercepted and refused.
Exercise
Why does functools.cached_property work as a non-data descriptor?
Show answer
On first access it computes the value and stores it in the instance __dict__ under its own name. Because it defines no __set__ or __delete__, later reads find that instance entry before the descriptor, so the computation is skipped.