← Back to Python, page 3

python-0059 · Hard senior

How do descriptors work, and how do property and methods rely on them?

A descriptor is an object defining __get__, and optionally __set__ or __delete__, stored as a class attribute; attribute access on instances then calls those methods. Data descriptors (with __set__) take priority over the instance dictionary, non-data descriptors do not. property, functions becoming bound methods, classmethod and staticmethod are all descriptors.

Full answer
python
class Positive:
    def __set_name__(self, owner, name):
        self.private = "_" + name
    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        return getattr(obj, self.private)
    def __set__(self, obj, value):
        if value <= 0:
            raise ValueError(f"{self.private[1:]} must be positive, got {value}")
        setattr(obj, self.private, value)

class Product:
    price = Positive()
    qty = Positive()
    def __init__(self, price, qty):
        self.price, self.qty = price, qty

p = Product(10, 3)
print(p.price * p.qty, vars(p))
try:
    p.qty = 0
except ValueError as e:
    print("ValueError:", e)
print(type(Product.__dict__["price"]).__name__, hasattr(Product.__init__, "__get__"))

Output:

text
30 {'_price': 10, '_qty': 3}
ValueError: qty must be positive, got 0
Positive True

__set_name__ (Python 3.6+) tells each descriptor its attribute name, so one Positive class validates both fields and stores values under _price and _qty, as vars(p) shows. Assigning 0 to qty goes through __set__ and is rejected. Accessing the attribute on the class returns the descriptor itself because obj is None. Plain functions have __get__, which is how p.method becomes a bound method with self filled in. Descriptors are how ORMs map columns to attributes.

python
class Positive:
    def __set_name__(self, owner, name):
        self.private = "_" + name
    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        return getattr(obj, self.private)
    def __set__(self, obj, value):
        if value <= 0:
            raise ValueError(f"{self.private[1:]} must be positive, got {value}")
        setattr(obj, self.private, value)

class Product:
    price = Positive()
    qty = Positive()
    def __init__(self, price, qty):
        self.price, self.qty = price, qty

p = Product(10, 3)
print(p.price * p.qty, vars(p))
try:
    p.qty = 0
except ValueError as e:
    print("ValueError:", e)
print(type(Product.__dict__["price"]).__name__, hasattr(Product.__init__, "__get__"))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Descriptors define __get__/__set__ on class attributes
  • Data descriptors override instance dicts
  • __set_name__ gives the attribute name
  • Functions are non-data descriptors
  • property is a descriptor

Common mistakes

  • Storing the value under the same name and recursing
  • Storing per-instance values on the descriptor itself

Follow-ups

  • How does attribute lookup order work exactly?
  • How do ORMs use descriptors?

Tips

  • Store per-instance data on the instance