Descriptors and Attribute Lookup
Trace how a descriptor controls attribute access for an instance.
python, descriptors, attributes, data modelAn attribute can run a protocol
A descriptor is an object that defines one or more of __get__,
__set__, and __delete__. When a descriptor is stored on a class,
ordinary attribute access can invoke these methods. Properties, functions,
and several other Python features use descriptor behaviour.
Python illustration
class Positive:
def __set_name__(self, owner, name):
self.name = name
def __get__(self, instance, owner):
if instance is None:
return self
return instance.__dict__[self.name]
def __set__(self, instance, value):
if value <= 0:
raise ValueError("value must be positive")
instance.__dict__[self.name] = value
class Reading:
pages = Positive()
def __init__(self, pages):
self.pages = pages
first = Reading(3)
second = Reading(5)
print(first.pages, second.pages)
Prepared output — not live execution:
3 5
Creating the class calls __set_name__ with the attribute name. Assignment
invokes __set__, which validates and stores the value in the particular
instance. Reading invokes __get__. A zero or negative value raises
ValueError; the example expects values that can be compared with zero.
See the reasoning
Trace descriptor access
Follow validation and instance-specific storage for two readings. This is a prepared demonstration, not live code execution.
Create the class
- Descriptorname: pagesCurrent focus
- firstnot yet created
- secondnot yet created
Python calls __set_name__ on the shared descriptor with the name pages.
Lookup order matters
A descriptor defining __set__ or __delete__ is a data descriptor.
In normal instance lookup, data descriptors take precedence over the
instance dictionary; non-data descriptors such as ordinary functions can
be shadowed by instance attributes. Custom __getattribute__ implementations
can change lookup behaviour. Access through the class passes None as the
instance in this example. Do not confuse per-instance storage with the
single descriptor object shared by the class.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
