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?
Keep reading
Related articles from the SudoSecurity blog.
Free-Threaded Python, Measured: Threads Finally Scale, and Your Unlocked Counter Finally Breaks
Python 3.14 made the no-GIL build officially supported, and 3.15 kept going. I ran the same CPU-bound job on standard and free-threaded builds of both: threads went from slower-than-serial to 1.9x faster, and a counter that never lost an update under the GIL lost 70% of them without it.
What is Python? Enterprise, Data Science, and the Backend of the Web
Python runs Instagram, Dropbox, Netflix, Spotify, and Reddit. It trains the models that power modern AI. It processes petabytes of data in enterprise pipelines. And I ignored it for years because I thought it was just for academics. Here is what changed my mind.
What Python 3.13 Shipped
The first release of Python 3.13 is now here as a Beta Release. This article is a rundown of all of the important changes and features that are being released in Python 3.13, along with what they mean for Python Developers. Please remember that this can change between
What Python 3.11 Actually Changed
The Python Programming Language releases a new version every year, with a feature-locked beta release in the first half of the year and the final release toward the end of the year. The feature set for Python 3.11 has just been finalized, with a beta version available for testing.