Skip to content

Python Descriptors: __get__, __set__, and __delete__

  • The descriptor protocol — __get__, __set__, __delete__ and their argument signatures.
  • The difference between data and non-data descriptors and why it changes attribute lookup.
  • How property, staticmethod, classmethod, and even plain instance methods are all descriptors.
  • How to build a reusable validated attribute and a one-time cached attribute with a descriptor.
  • When a descriptor is the right abstraction versus @property or __init__ validation.

A descriptor is an object assigned as a class attribute whose class defines __get__, __set__, or __delete__. When you read or write instance.attr, Python checks the class first; if attr is a descriptor, Python delegates the access to the descriptor’s method instead of returning a plain stored value. This is the mechanism underneath @property, @staticmethod, @classmethod, and ordinary method binding. Descriptors let you write one class that encapsulates a rule — validation, type coercion, caching — and then attach instances of it to as many attributes as needed.

Without descriptors, attaching validation to an attribute means writing get_x and set_x methods. Callers lose the natural obj.x syntax, and the rule lives in the method pair, not reusable across attributes. @property fixes one attribute at a time, but you cannot share one @property across several attributes, and you cannot attach the same “must be non-negative” rule to amount, discount, and shipping without copying the decorator block onto each.

Descriptors solve reuse: define the rule once in a descriptor class, then drop instances of it onto as many attributes as you like. They also explain the language itself — once you know descriptors, @property, method binding, and ORM field types all stop being magic and become the same mechanism viewed from different angles.

The protocol has three optional methods:

class Descriptor:
def __get__(self, instance, owner=None):
...
def __set__(self, instance, value):
...
def __delete__(self, instance):
...
  • __get__(self, instance, owner) runs on instance.attr (and Class.attr). instance is the object, or None when accessed on the class; owner is the class.
  • __set__(self, instance, value) runs on instance.attr = value.
  • __delete__(self, instance) runs on del instance.attr.

The data/non-data split is what makes lookup order consistent:

  • A data descriptor defines __set__ or __delete__. It takes priority over the instance __dict__, so it can intercept assignment.
  • A non-data descriptor defines only __get__. The instance __dict__ shadows it, so an instance attribute with the same name can override it.

The simplified lookup order is: a data descriptor on the class (and bases) wins first, then the instance __dict__, then a non-data descriptor on the class, then a plain class attribute. This is why you can override a method by setting an instance attribute of the same name (the method is a non-data descriptor) but you cannot override a property the same way (a property is a data descriptor).

property is itself a descriptor class that implements all three methods — @property and @x.setter just construct one. A plain function is a non-data descriptor: instance.method triggers the function’s __get__, which returns a bound method with self already filled in. That is how methods know their instance.

The descriptor object lives on the class, shared by all instances, which is why __get__ and __set__ receive instance: to know whose data to touch. Store per-instance values on instance.__dict__ under a distinct key, not on the descriptor itself. __set_name__ (Python 3.6+) hands the descriptor its attribute name at class-creation time, so you can derive that storage key without passing it manually.

OrdersPortal orders have monetary fields — amount, discount, shipping — that must be non-negative decimals, with amount required to be positive. Define the rule once and reuse it across all three fields.

from decimal import Decimal
class NonNegativeDecimal:
def __set_name__(self, owner, name):
self.storage = f"_{name}"
self.name = name
def __get__(self, instance, owner=None):
if instance is None:
return self
return getattr(instance, self.storage, Decimal("0"))
def __set__(self, instance, value):
value = value if isinstance(value, Decimal) else Decimal(str(value))
if value < 0:
raise ValueError(f"{self.name} must be >= 0, got {value}")
setattr(instance, self.storage, value)
class PositiveDecimal(NonNegativeDecimal):
def __set__(self, instance, value):
value = value if isinstance(value, Decimal) else Decimal(str(value))
if value <= 0:
raise ValueError(f"{self.name} must be > 0, got {value}")
setattr(instance, self.storage, value)
class Order:
amount = PositiveDecimal()
discount = NonNegativeDecimal()
shipping = NonNegativeDecimal()
def __init__(self, amount, discount="0", shipping="0"):
self.amount = amount
self.discount = discount
self.shipping = shipping
@property
def total(self):
return self.amount - self.discount + self.shipping

Driving it:

o = Order(amount="199.99", discount="10.00", shipping="5.50")
print(o.total) # Decimal('195.49')
o.discount = "-5" # raises ValueError: discount must be >= 0

The validation rule is written once and applied to three fields. Adding a fourth monetary field is a one-line class attribute.

A descriptor is also a clean way to build a cached, computed attribute — computed once per instance and then stored:

class CachedField:
def __set_name__(self, owner, name):
self.storage = f"_cached_{name}"
self.name = name
def __get__(self, instance, owner=None):
if instance is None:
return self
try:
return getattr(instance, self.storage)
except AttributeError:
pass
value = self.compute(instance)
setattr(instance, self.storage, value)
return value
def compute(self, instance):
raise NotImplementedError

Subclass it to cache an expensive value, for example a signed shipping rate quote that should be computed once per order and then reused.

  • Use __set_name__ to learn the attribute name at class-creation time, so callers do not have to pass it.
  • Store per-instance values under a distinct, prefixed key to avoid clashing with the public attribute name (which would cause infinite recursion in __set__).
  • Handle instance is None in __get__ so class-level access and introspection tools return the descriptor instead of crashing.
  • When staging writes (ORM-style), have __set__ mark the instance dirty instead of writing straight to storage, so a save step can flush changes.
  • Combine descriptors with __slots__ by listing the storage keys in __slots__ so the instance keeps the memory savings.
  • Storing the value on the descriptor instance itself — it is shared across all instances, so every order would see the same single value.
  • Forgetting to handle instance is None in __get__ — breaks class-level access and tools like help().
  • Defining only __get__ and expecting assignment to be intercepted — only data descriptors win over __dict__.
  • Using the public attribute name as the storage key and recursing forever inside __set__.
  • Reaching for a descriptor when a single @property or __init__ validation would do — descriptors pay off on reuse, not on a one-off rule.

Use descriptors when:

  • The same rule applies to several attributes or classes (validation, type coercion, caching, ORM fields).
  • You are building library or DSL machinery — ORMs, config systems, validators.
  • You need to intercept attribute access uniformly across a class hierarchy.

Avoid descriptors when:

  • One attribute needs one rule — use @property.
  • Validation belongs at construction — use __init__ or __post_init__.
  • A plain method or dataclass field expresses the intent clearly enough.

The descriptor protocol (__get__, __set__, __delete__) is part of the language and fully supported on Python 3.9 through 3.14. __set_name__ (PEP 487) arrived in Python 3.6. functools.cached_property (3.8+) builds on the same protocol. No third-party packages are required.

  1. What is the difference between a data descriptor and a non-data descriptor, and why does it matter for attribute lookup? A data descriptor defines __set__ or __delete__; a non-data descriptor defines only __get__. It matters because Python checks data descriptors on the class before the instance __dict__, but checks the instance __dict__ before non-data descriptors. So an instance attribute with the same name can shadow a non-data descriptor (which is why you can override a method by setting an instance attribute) but cannot shadow a data descriptor (which is why you cannot override a property that way).

  2. Is @property implemented with descriptors? Yes. property is a class that implements __get__, __set__, and __delete__. The @property and @x.setter decorators just construct a property instance and assign it as a class attribute — a descriptor. That is why assigning to a property that has no setter raises AttributeError: the data descriptor intercepts the assignment and there is no __set__ to run.

  3. Where does a descriptor store its data, and why? The descriptor object lives on the class and is shared by all instances, so it cannot store per-instance state on itself. It stores each instance’s value in that instance’s __dict__ under a separate key (commonly a prefixed name learned via __set_name__). __get__ and __set__ receive the instance argument precisely so they know whose value to read or write.

  4. Senior scenario: a teammate reports that order.amount = 5 silently does nothing — the value never sticks. You implemented amount as a descriptor that stores in self._value. What went wrong and how do you fix it? The descriptor stored the value on itself. Because one descriptor instance is shared across all Order instances, every read and write touches that single shared slot — assignments appear not to stick because they overwrite the same shared field, and reads return whatever any instance last wrote. The fix is to store per-instance: capture the attribute name with __set_name__, and in __set__ write to instance.__dict__ under a distinct key (for example f"_{name}"), reading it back in __get__. Each instance then keeps its own value, and the descriptor holds only the rule, not the data.

  • A descriptor is a class-level object that intercepts attribute access through __get__, __set__, and __delete__.
  • Data descriptors beat the instance __dict__; non-data descriptors lose to it.
  • @property, @staticmethod, @classmethod, and method binding are all descriptors.
  • Store per-instance data on the instance (via __set_name__), never on the shared descriptor.
  • Use descriptors for reuse across many attributes; use @property for a single attribute.
  • Property decorator — the one-attribute convenience built on descriptors
  • Magic methods — dunder methods and attribute-access hooks
  • dataclasses — __post_init__ validation as a simpler alternative
  • Metaclasses — automating descriptor creation at class-creation time