Lesson 41 of 52Python under the hood
Descriptors and Attribute Lookup
Learn exactly what obj.attr does, write your own descriptors, and see how methods, property, __slots__ and ORM fields all work underneath.
You open a SQLAlchemy model and notice something odd. User.email (on the class) is a strange column object you can put into a query, but user.email (on an instance) is just a string. Same name, two completely different things. A few weeks later you need the same validation (a positive integer, a trimmed string) on twelve fields across four classes, and writing twelve @property pairs feels wrong. Both puzzles have one answer: the descriptor protocol, the small hook that sits under every dot in Python. Once you understand it, methods, property, classmethod, __slots__ and ORM fields stop being magic and become one mechanism you can use yourself. This last unit is optional on a first pass: it explains the machinery under features you already use.
What obj.attr actually does
You learnt in The Python Memory Model that an instance keeps its attributes in a dict, obj.__dict__. It is tempting to think obj.attr just reads that dict. It does not. When you write obj.attr, Python calls type(obj).__getattribute__(obj, "attr"), and the default implementation in object follows a fixed order:
- Look up
"attr"on the class, walkingtype(obj).__mro__(the method resolution order you met in Inheritance and Composition). Do not use it yet; just remember what was found. - If the class attribute is a data descriptor (it defines
__set__or__delete__), call its__get__and return the result. It wins over everything. - Otherwise, if
"attr"is inobj.__dict__, return that value. - Otherwise, if the class attribute is a non-data descriptor (it only defines
__get__), call its__get__and return the result. - Otherwise, if a plain class attribute was found, return it.
- Otherwise, raise
AttributeError. If the class defines__getattr__, Python catches that error and calls__getattr__(obj, "attr")as a last resort.
Every dot calls __getattribute__. The first thing it does is look the name up on the class, through the whole MRO, before touching the instance.
The precedence explains things you have seen without noticing. You can shadow a method by assigning to the instance (obj.save = None hides save), because methods are non-data descriptors and the instance dict beats them. You cannot shadow a property that way, because a property is a data descriptor and it beats the instance dict.
Press Run (⌘ Enter) to see what happens.Writes are simpler than reads. obj.attr = value calls type(obj).__setattr__, which looks for a data descriptor on the class and calls its __set__. If there is none, the value goes into obj.__dict__. There is no "non-data" step for writes, which is exactly why a method can be shadowed.
What does this print?
class Config:
debug = False
@property
def env(self):
return "prod"
c = Config()
c.__dict__.update(debug=True, env="dev")
print(c.debug, c.env, Config.debug)The four hooks: __getattr__, __getattribute__, __setattr__, __delattr__
Classes can customise each part of attribute access. Two of these hooks have similar names and very different costs.
__getattr__(self, name) runs only when normal lookup fails. That makes it the right tool for fallbacks: a proxy that forwards unknown attributes to a wrapped object, a lazy loader that imports a heavy module on first use, or an API client where client.users builds a sub-client. Because it never runs for attributes that exist, it costs nothing in the common case.
__getattribute__(self, name) runs for every attribute access, including self.__dict__ and method lookups. Override it and any self.x inside it calls it again, which is an infinite recursion. If you must override it, get real attributes through super().__getattribute__(name) or object.__getattribute__(self, name). In application code you almost never need it; it is for tracing, security sandboxes and test doubles.
__setattr__(self, name, value) runs on every assignment, including the ones in your own __init__. The same recursion trap applies: self.x = v inside __setattr__ calls __setattr__ again. Store through super().__setattr__(name, value). __delattr__ is the matching hook for del obj.attr.
Press Run (⌘ Enter) to see what happens.Notice getattr(obj, name, default). The three-argument form returns the default instead of raising, and it is how you read an attribute whose name is in a variable. Do not reach for __dict__ lookups for that; they skip descriptors and miss class attributes.
The descriptor protocol
A descriptor is any object, stored as a class attribute, whose type defines at least one of these methods:
__get__(self, instance, owner): called on read.instanceis the object the attribute was read through, orNoneif it was read on the class itself.owneris the class.__set__(self, instance, value): called on write through an instance.__delete__(self, instance): called ondel instance.attr.__set_name__(self, owner, name): called once, when the class is created, telling the descriptor which class it lives in and which name it was assigned to. This arrived in 3.6 and is why modern descriptors no longer need you to repeat the field name.
Defining __set__ or __delete__ makes it a data descriptor, which wins over the instance dict. Only __get__ makes it a non-data descriptor, which the instance dict can shadow. The rule is about which methods the type defines, not what they do: a __set__ that just raises still makes a read-only data descriptor, and that is exactly how a property without a setter works.
A descriptor only works as a class attribute. Put one in an instance dict and Python treats it as an ordinary value. This catches people out when they try to attach a property to a single object at runtime.
Press Run (⌘ Enter) to see what happens.The if instance is None: return self line is a convention you should always follow. It means Order.total returns the descriptor itself, so documentation tools, help(), introspection and frameworks can find and inspect it. SQLAlchemy uses the same branch to give you a column expression on the class and a value on the instance: the User.email versus user.email puzzle from the start of this lesson.
Build a reusable validated field
Here is the twelve-properties problem solved properly. One descriptor class, reused on every field that needs the rule.
Press Run (⌘ Enter) to see what happens.Two design choices are worth understanding, because interviewers like to probe them.
Where does the value live? It cannot live on the descriptor (self.value = ...), because there is one descriptor per class, shared by every instance. Store it there and every LineItem has the same quantity: a classic bug. Store it on the instance instead. Here it goes under a private name (_quantity). Another common choice is the same name in instance.__dict__, which works because a data descriptor wins over the instance dict anyway, so reads still go through __get__.
Why isinstance(value, bool)? Because True is an int in Python. Without that check, item.quantity = True would store 1.
How does this compare with the alternatives?
propertyis perfect for one computed or validated attribute. It is itself a descriptor, written for you. The cost is repetition once the same rule appears many times.- A custom descriptor packages a rule once and reuses it everywhere, and it validates on every assignment, not only at construction.
- Pydantic (and
attrsvalidators) validate a whole object from external data, give structured error messages for every bad field at once and generate JSON Schema. For data arriving at an API boundary that is usually the better tool. Descriptors fit domain objects inside your code, and they are how such libraries are built.
self.value = value in __set__ and return self.value in __get__. What goes wrong?You already use descriptors every day
The descriptor protocol is not an advanced corner of Python. It is how the core of the object model works.
Functions become methods. A plain function is a non-data descriptor. When you read greeter.hello through an instance, function.__get__(greeter, Greeter) returns a bound method: a small object that remembers the function and the instance. Calling it calls the function with the instance as the first argument. That is the whole answer to "how does self get passed?". Nothing special happens at the call; it happened at the dot.
property is a data descriptor class. @property creates one wrapping your getter; .setter returns a copy with a setter added. Without a setter, its __set__ raises AttributeError.
classmethod is a descriptor whose __get__ binds the function to the owner class instead of the instance. staticmethod is a descriptor whose __get__ returns the plain function, unbound.
__slots__ creates one member descriptor per slot on the class, as you will see in the next section.
functools.cached_property is a non-data descriptor. On first access it computes the value and stores it in the instance dict under the same name. From then on, the instance dict wins over the non-data descriptor, so later reads never call it again. That trick is the whole implementation. It also means the class needs a __dict__, and you clear the cache with del obj.attr.
Press Run (⌘ Enter) to see what happens.One recent change shows how deep this goes. In Python 3.14, functools.partial objects became method descriptors, so a partial stored as a class attribute now binds self like a function does. The 3.14 release notes tell you to wrap it in staticmethod() to keep the old behaviour. Small descriptor details can be a real upgrade concern.
Match each built-in to what its __get__ returns when read through an instance.
__slots__: no __dict__, less memory
By default every instance carries its own dict. That is flexible but not free: each dict costs memory, and with millions of small objects (rows from a file, nodes in a graph, events in a simulation) it adds up. __slots__ tells Python the exact set of attribute names up front. Python then reserves fixed space in each instance and creates a member descriptor on the class for each name. There is no per-instance __dict__.
Press Run (⌘ Enter) to see what happens.The exact byte counts depend on the Python version, so measure your own case with tracemalloc rather than trusting a number from a blog post. The direction is consistent: slotted instances are smaller and attribute access is a little faster.
The gotchas are where seniors earn their keep:
- Inheritance leaks the dict back. If any class in the hierarchy lacks
__slots__, instances get a__dict__anyway. A subclass that does not declare__slots__(even an empty tuple) silently restores it. - Do not repeat a parent's slot in a child. It wastes space and hides the parent's descriptor.
- No dynamic attributes, which breaks some libraries and monkeypatching in tests. Add
"__dict__"to the slots if you need both, at the cost of the saving. - No weak references unless you include
"__weakref__"in the slots. cached_propertydoes not work, because it needs the instance dict.- Multiple inheritance: two bases that both have non-empty slots cannot be combined; Python raises a layout conflict
TypeError.
For data classes, @dataclass(slots=True) (3.10) builds the slotted class for you. You saw it in Dataclasses. Note that it creates a new class behind the scenes, which is why a zero-argument super() inside such a class could fail on older versions. Check the dataclasses docs for your version if you hit that.
Python reads obj.name on an instance. Order the places it checks, first to last.
- Tap the steps below in the right order.
Where you meet descriptors at work
ORMs. In SQLAlchemy 2.x, a declared column such as email: Mapped[str] = mapped_column() becomes an instrumented attribute on the class. Read on the class, it returns an expression you can use in select(User).where(User.email == x). Read on an instance, it returns the loaded value, and setting it records the change so the session knows what to flush. Lazy-loaded relationships are descriptors that run a query on first access, which is how the N+1 problem sneaks in: every order.customer in a loop is a descriptor call that may hit the database.
Django model fields work the same way: the field's descriptor on the model class handles reading, deferred loading and related-object lookups.
Pydantic and dataclasses mostly avoid per-field descriptors for speed and generate __init__ instead, but both interact with descriptors you put on the class, and both are built on the class-creation machinery covered in How Classes Are Made.
Your own code. Good everyday uses: a validated field reused across many classes, a unit-carrying value, a lazily computed attribute (usually just cached_property), and a class-level registry entry. Poor uses: anything a single property handles, or hiding expensive I/O behind what looks like a cheap attribute.
How CPython makes this fast
Walking the MRO on every dot would be slow, so CPython caches type lookups: each type has a version tag, and a global method cache maps (type version, name) to the class attribute found. Changing a class attribute bumps the version and invalidates those entries, which is one reason monkeypatching classes in hot loops is a bad idea.
The bytecode helps too. obj.method() compiles to a LOAD_ATTR with a method flag followed by CALL. The specialising interpreter (3.11 and later) notices when a function is found on the class and nothing shadows it in the instance, and then skips creating the bound method object entirely: it pushes the function and self and calls directly. Semantically you still get a bound method; physically, CPython optimises it away. Run dis.dis on a method call to see the instructions in your version.
- descriptor
- An object stored on a class whose type defines
__get__,__set__or__delete__, so it controls access to that attribute. - data descriptor
- A descriptor with
__set__or__delete__. It wins over the instance dict (property, slots, ORM columns). - non-data descriptor
- A descriptor with only
__get__. The instance dict can shadow it (functions,cached_property). - __set_name__
- Called once at class creation to tell a descriptor its owner class and attribute name.
- bound method
- The object
function.__get__returns: the function plus the instance it will receive asself. - __getattr__ vs __getattribute__
__getattr__is a fallback for missing names;__getattribute__runs on every access and easily recurses.- __slots__
- A fixed list of attribute names that replaces the per-instance
__dict__with member descriptors, saving memory.