Python Descriptors and Attribute Access
A descriptor is an object that controls attribute access by defining one or more of __get__, __set__, and __delete__. When that object is placed on a class, Python can run its code when an attribute is read, assigned, or deleted.
Descriptors solve a recurring design problem: keeping an attribute-looking interface while adding behavior behind it. Without them, callers would need to invoke getter and setter methods explicitly, and Python methods would not automatically receive their instance as self.
The basic protocol
A descriptor is normally stored as a class attribute:
class LoggedValue:
def __get__(self, instance, owner):
print("reading value")
return instance.__dict__["_value"]
def __set__(self, instance, value):
print("writing value")
instance.__dict__["_value"] = value
class Device:
temperature = LoggedValue()
For an instance of Device, these expressions use the descriptor:
device = Device()
device.temperature = 21 # calls LoggedValue.__set__
print(device.temperature) # calls LoggedValue.__get__
The descriptor methods receive more context than an ordinary function:
instanceis the object whose attribute is being accessed, such asdevice.owneris the class, such asDevice.
When the attribute is accessed through the class—Device.temperature—Python calls __get__ with instance set to None and owner set to Device. Descriptors commonly return themselves in that case, allowing inspection or further configuration.
__delete__ handles del device.temperature:
class RequiredValue:
def __get__(self, instance, owner):
if instance is None:
return self
return instance.__dict__["_value"]
def __set__(self, instance, value):
if value is None:
raise ValueError("value is required")
instance.__dict__["_value"] = value
def __delete__(self, instance):
instance.__dict__.pop("_value", None)
A descriptor only needs to implement the operations it supports. An object with __get__ is a read descriptor; adding __set__ or __delete__ enables the corresponding operations.
What happens during attribute access
The syntax device.temperature looks simple, but Python must decide where temperature comes from. In broad terms, instance lookup considers:
- A data descriptor on the class. This is a descriptor that defines
__set__or__delete__; its__get__takes priority. - The instance's attribute storage, usually
device.__dict__. - A non-data descriptor or another class attribute.
That priority rule matters. A data descriptor cannot be silently overridden by an entry in the instance dictionary. This is useful for managed values such as validated fields. A descriptor with only __get__ is a non-data descriptor, so an instance attribute of the same name can take precedence over it.
For assignment, such as device.temperature = 21, Python first looks for a data descriptor on the class. If it finds one, it calls __set__. Otherwise, it normally stores the value in the instance dictionary. For deletion, del device.temperature similarly calls __delete__ when available; otherwise Python removes the instance attribute if one exists.
These rules are implemented by the machinery behind object.__getattribute__, object.__setattr__, and object.__delattr__. You usually do not call those methods directly, but they explain why overriding attribute access can change descriptor behavior—and why calling super() correctly is important when doing so.
The descriptor must be an attribute of the class, not merely an object placed in an instance attribute. Python discovers descriptors while looking up the class attribute.
Properties are descriptors
A property is Python's built-in, familiar example. It lets a class expose method-backed behavior with attribute syntax:
class Account:
def __init__(self, cents):
self._cents = cents
@property
def dollars(self):
return self._cents / 100
@dollars.setter
def dollars(self, value):
if value < 0:
raise ValueError("balance cannot be negative")
self._cents = round(value * 100)
dollars is not stored as a normal value on the class. The decorators create a property descriptor. Reading account.dollars invokes its getter through __get__; assigning to it invokes its setter through __set__. If no setter was defined, assignment raises an error instead of creating an unrelated instance attribute. This preserves a clean public interface while allowing validation, conversion, lazy computation, or compatibility logic behind it.
Why methods bind self
Ordinary functions defined in a class are descriptors too. A function implements __get__, which changes what you receive depending on how you access it:
class Worker:
def run(self):
return "running"
worker = Worker()
worker.run() # Python supplies worker as self
Worker.run(worker) # equivalent explicit form
Worker.run produces the function in its class-level form. worker.run produces a bound method—a callable that remembers worker and passes it as the first argument. That automatic binding is descriptor behavior, not a special rule attached only to the spelling of def.
ORM fields use the same mechanism
Object-relational mappers (ORMs) represent database rows as Python objects. A model declaration might look like this:
class User(Model):
email = StringField(unique=True)
created_at = DateTimeField()
An ORM field is often a descriptor. On user.email, its __get__ can read a value from the model's internal row data, fetch a deferred column, or convert a database value into a Python value. On user.email = value, __set__ can validate and normalize the value, then mark the model as changed. __delete__ may clear a value or represent a database NULL.
The descriptor lets the model author write user.email while the framework controls storage, validation, and persistence. The same pattern explains many error messages involving “descriptor,” “read-only attribute,” or a property without a setter: Python has reached an object responsible for that attribute operation, and that object's protocol has rejected or handled it.