Skip to content

Lesson 4 of 20 · 18m

Descriptors: The Machinery Under property

Descriptors are the __get__/__set__ protocol that makes property, bound methods, and ORM fields work — write one and the class machinery stops being magic.

obj.x = 5 is not a dictionary write. It is a protocol call: if type(obj).__dict__ holds a data descriptor named x, Python calls x.__set__(obj, 5) and the instance __dict__ never sees the assignment. property, classmethod, staticmethod, functools.cached_property, every ORM field you have ever typed — all of them are this one protocol wearing different clothes.

The protocol

A descriptor is any object whose class implements __get__(self, obj, owner). Add __set__ or __delete__ and it becomes a data descriptor. Attribute lookup resolves in a fixed order: data descriptor → instance __dict__ → non-data descriptor → class attribute → __getattr__. That ordering explains the weirdest asymmetry in Python: functions are non-data descriptors, so instance.method = lambda: ... shadows the class method — but instance.prop = 5 on a property raises AttributeError, because the data descriptor beats the instance dictionary even when the property has no setter. A read-only property still defines __set__ — that's what makes it data.

__get__ is also what makes methods work at all: obj.method is really function.__get__(obj, type(obj)), which produces a bound method — the function with self pre-filled via types.MethodType. staticmethod is a descriptor whose __get__ returns the function unbound; classmethod binds the class instead of the instance. There is no method machinery in the interpreter beyond this.

Write one

class Upper:
    def __set_name__(self, owner, name):
        self.name = name            # learn the attribute name at class creation
    def __get__(self, obj, owner):
        if obj is None:
            return self             # User.name returns the descriptor itself
        return obj.__dict__.get(self.name)
    def __set__(self, obj, value):
        obj.__dict__[self.name] = value.upper()

class User:
    name = Upper()

__set_name__ fires during class-body execution (3.6+) — this is exactly how name = Field() learns it is called name without you passing a string. SQLAlchemy's Column, Pydantic's fields, attrs attributes and Django's Field all hang validation, defaults, and aliasing on this hook or its cousins. When the framework reads like magic, the mechanism is a descriptor.

SQLAlchemy shows how far it goes: User.name on the class returns an InstrumentedAttribute, and User.name == "x" returns a SQL clause object, not False — the descriptor's __get__ returns an expression object whose __eq__ builds SQL. __delete__ completes the trio: del obj.attr routes through it the same way assignment routes through __set__.

The costs

obj.x through a descriptor is a function call — cheap, but a loop that reads self.prop a million times pays a million calls; hoist it into a local inside the hot loop. functools.cached_property (3.8) computes once and stores into __dict__ — but it is a non-data descriptor, so it needs an instance dict: under __slots__ it fails unless you add "__dict__" to the slots. Non-data also means a plain obj.x = 5 assignment overwrites the cache silently — sometimes the feature, sometimes the bug. And __getattribute__ — the always-called cousin of __getattr__ — recurses forever if you touch self.anything inside it; super().__getattribute__(name) is the way out.

PEP 562 (3.7) gave modules __getattr__ too — def __getattr__(name) at module top level is how libraries ship deprecation shims and lazy submodules (importlib machinery can then defer an expensive import until the name is actually touched).

When you need the attribute without firing the protocol — debugging a descriptor that raises, inspecting a lazy __getattr__ — inspect.getattr_static(obj, "x") walks the lookup chain and returns the raw descriptor object instead of calling __get__.

The practice

property for cheap computed attributes, cached_property for expensive ones. Reach for a descriptor before a metaclass — validation, unit-aware types, __set_name__-registered fields all live at this layer. __getattr__ for "attribute doesn't exist yet" fallback; __getattribute__ only after you've measured why nothing cheaper will do.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.