Python Descriptors: __get__, __set__, and __delete__
What you’ll learn
Section titled “What you’ll learn”- 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
@propertyor__init__validation.
Summary
Section titled “Summary”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.
The problem it solves
Section titled “The problem it solves”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.
How it works
Section titled “How it works”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 oninstance.attr(andClass.attr).instanceis the object, orNonewhen accessed on the class;owneris the class.__set__(self, instance, value)runs oninstance.attr = value.__delete__(self, instance)runs ondel 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.
Realistic example
Section titled “Realistic example”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.shippingDriving 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 >= 0The 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 NotImplementedErrorSubclass it to cache an expensive value, for example a signed shipping rate quote that should be computed once per order and then reused.
Production patterns
Section titled “Production patterns”- 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 Nonein__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.
Common mistakes
Section titled “Common mistakes”- 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 Nonein__get__— breaks class-level access and tools likehelp(). - 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
@propertyor__init__validation would do — descriptors pay off on reuse, not on a one-off rule.
When to use it and when not to
Section titled “When to use it and when not to”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.
Compatibility
Section titled “Compatibility”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.
Interview questions
Section titled “Interview questions”-
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). -
Is
@propertyimplemented with descriptors? Yes.propertyis a class that implements__get__,__set__, and__delete__. The@propertyand@x.setterdecorators just construct apropertyinstance and assign it as a class attribute — a descriptor. That is why assigning to a property that has no setter raisesAttributeError: the data descriptor intercepts the assignment and there is no__set__to run. -
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 theinstanceargument precisely so they know whose value to read or write. -
Senior scenario: a teammate reports that
order.amount = 5silently does nothing — the value never sticks. You implementedamountas a descriptor that stores inself._value. What went wrong and how do you fix it? The descriptor stored the value on itself. Because one descriptor instance is shared across allOrderinstances, 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 toinstance.__dict__under a distinct key (for examplef"_{name}"), reading it back in__get__. Each instance then keeps its own value, and the descriptor holds only the rule, not the data.
Key takeaways
Section titled “Key takeaways”- 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
@propertyfor a single attribute.
Related pages
Section titled “Related pages”- 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