Sub topic 2
Data and Non-Data Descriptors
Assume you know Python classes, instances, inheritance, and special methods. A descriptor is a class object that controls attribute access through methods such as __get__ and __set__.
Data and non-data descriptors
A data descriptor defines __set__ or __delete__ as well as __get__. It takes priority over an attribute stored in an instance's __dict__.
A non-data descriptor defines only __get__. An instance attribute with the same name takes priority over it.
| Descriptor kind | Required methods | Priority over instance `__dict__` |
|---|---|---|
| Data descriptor | `__get__` plus `__set__` or `__delete__` | Yes |
| Non-data descriptor | `__get__` only | No |
class Data:
def __get__(self, obj, objtype=None):
return "data"
def __set__(self, obj, value):
obj.__dict__["value"] = value
class NonData:
def __get__(self, obj, objtype=None):
return "non-data"
class Example:
data = Data()
non_data = NonData()
item = Example()
item.__dict__["data"] = "instance data"
item.__dict__["non_data"] = "instance non-data"
print(item.data) # data
print(item.non_data) # instance non-dataThe complete lookup order
obj.name enters object.__getattribute__ unless the class overrides it. Python searches the class's method resolution order (MRO), which lists the class and its base classes.
The effective order is:
- Find a class attribute in the MRO.
- If it is a data descriptor, call its
__get__. - Otherwise, check
obj.__dict__. - If the instance has no value, use a non-data descriptor or plain class attribute.
- If lookup raises
AttributeError, call__getattr__if the class defines it.
Writing a descriptor
Use __set_name__ to learn the attribute's declared name. Store values on each instance, not on the descriptor object. The descriptor is normally shared by every instance.
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(f"{self.private_name[1:]} must be positive")
setattr(obj, self.private_name, value)
class Item:
price = Positive()
def __init__(self, price):
self.price = price
item = Item(9.5)
print(item.price)How functions become bound methods
Functions stored in a class are non-data descriptors. Their __get__ method creates a bound method containing both the function and the instance. That is why item.method() automatically supplies item as self.
Exercise
Which wins when an instance attribute has the same name as a data descriptor?
Show answer
The data descriptor wins because Python checks it before the instance dictionary.