Skip to content

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.

20 min read0/4 questions

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:

  1. Look up "attr" on the class, walking type(obj).__mro__ (the method resolution order you met in Inheritance and Composition). Do not use it yet; just remember what was found.
  2. If the class attribute is a data descriptor (it defines __set__ or __delete__), call its __get__ and return the result. It wins over everything.
  3. Otherwise, if "attr" is in obj.__dict__, return that value.
  4. Otherwise, if the class attribute is a non-data descriptor (it only defines __get__), call its __get__ and return the result.
  5. Otherwise, if a plain class attribute was found, return it.
  6. Otherwise, raise AttributeError. If the class defines __getattr__, Python catches that error and calls __getattr__(obj, "attr") as a last resort.
The lookup chain behind obj.attr
obj.attr: __getattribute__obj.attr__getattribute__Search the MRO: type(obj).__mro__Search the MROtype(obj).__mro__Data descriptor: has __set__: call __get__Data descriptorhas __set__: call __get__Instance __dict__: obj.__dict__['attr']Instance __dict__obj.__dict__['attr']Non-data / class attr: methods, constantsNon-data / class attrmethods, constants__getattr__: only if all failed__getattr__only if all failed1st2nd3rdAttributeError

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.

1/5

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.

Python
class Account: kind = "standard" # plain class attribute def describe(self): # function: non-data descriptor return "a method" @property def balance(self): # property: data descriptor return 100 acct = Account()acct.__dict__["kind"] = "premium" # write straight into the instance dictacct.__dict__["describe"] = "shadowed"acct.__dict__["balance"] = -5 print(acct.kind) # instance dict beats a plain class attributeprint(acct.describe) # instance dict beats a non-data descriptorprint(acct.balance) # data descriptor beats the instance dictprint(Account.kind) # the class itself is untouched
Output
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.

Predict the outputPython

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)
Need a nudge? Hints walk you through it.

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.

Python
class Lazy: """Forward unknown attributes to an object built on first use.""" def __init__(self, factory): object.__setattr__(self, "_factory", factory) object.__setattr__(self, "_target", None) def __getattr__(self, name): # only called for missing names if self._target is None: print(" building the real object...") object.__setattr__(self, "_target", self._factory()) return getattr(self._target, name) def __setattr__(self, name, value): # block accidental writes raise AttributeError(f"{type(self).__name__} is read-only: {name}") config = Lazy(lambda: {"region": "eu-west-2", "retries": 3})print("proxy created")print(config.get("region")) # triggers the build onceprint(config.get("retries")) # already builttry: config.region = "us-east-1"except AttributeError as e: print("AttributeError:", e) print(getattr(config, "keys")() is not None)print(getattr(object(), "missing", "default")) # the three-argument form
Output
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. instance is the object the attribute was read through, or None if it was read on the class itself. owner is the class.
  • __set__(self, instance, value): called on write through an instance.
  • __delete__(self, instance): called on del 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.

Python
class Traced: def __set_name__(self, owner, name): print(f"__set_name__: {owner.__name__}.{name}") self.name = name def __get__(self, instance, owner): if instance is None: print(f"__get__ on the class {owner.__name__}") return self print(f"__get__ on an instance of {owner.__name__}") return instance.__dict__.get(self.name, 0) def __set__(self, instance, value): print(f"__set__ {self.name} = {value}") instance.__dict__[self.name] = value print("defining the class")class Order: total = Traced() print("using it")o = Order()o.total = 42print(o.total)print(type(Order.total).__name__)
Output
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.

Python
class Positive: """A field that only accepts numbers greater than zero.""" def __init__(self, kind=int): self.kind = kind def __set_name__(self, owner, name): self.public = name self.private = "_" + name def __get__(self, instance, owner): if instance is None: return self try: return getattr(instance, self.private) except AttributeError: raise AttributeError(self.public) from None def __set__(self, instance, value): if not isinstance(value, self.kind) or isinstance(value, bool): raise TypeError(f"{self.public} must be {self.kind.__name__}, got {value!r}") if value <= 0: raise ValueError(f"{self.public} must be > 0, got {value}") setattr(instance, self.private, value) class LineItem: quantity = Positive() price = Positive(float) def __init__(self, sku, quantity, price): self.sku = sku self.quantity = quantity # goes through Positive.__set__ self.price = price item = LineItem("BK-1", 3, 9.5)print(item.quantity, item.price, vars(item)) for bad in (0, "3", True): try: item.quantity = bad except (TypeError, ValueError) as e: print(type(e).__name__, e)
Output
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?

  • property is 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 attrs validators) 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.
Quick check
A teammate's descriptor does self.value = value in __set__ and return self.value in __get__. What goes wrong?
Need a nudge? A hint rules out a wrong answer.

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.

Python
from functools import cached_property class Greeter: def __init__(self, name): self.name = name def hello(self): return f"hello, {self.name}" @cached_property def report(self): print(" computing report...") return self.name.upper() g = Greeter("ada")raw = Greeter.__dict__["hello"]print(type(raw).__name__, hasattr(raw, "__get__"), hasattr(raw, "__set__")) bound = raw.__get__(g, Greeter) # what g.hello does for youprint(type(bound).__name__, bound.__self__ is g, bound())print(g.hello == bound, Greeter.hello is raw) print(g.report)print(g.report) # served from g.__dict__ nowprint("report" in vars(g))del g.report # clear the cacheprint(g.report) for name in ("hello", "report"): attr = Greeter.__dict__[name] print(name, type(attr).__name__, "data" if hasattr(type(attr), "__set__") else "non-data")
Output
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 the pairs0/5 matched

Match each built-in to what its __get__ returns when read through an instance.

Choose an item, then its match on the other side.

__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__.

Python
import sys class PointDict: def __init__(self, x, y): self.x, self.y = x, y class PointSlots: __slots__ = ("x", "y") def __init__(self, x, y): self.x, self.y = x, y a, b = PointDict(1, 2), PointSlots(1, 2)print(sys.getsizeof(a) + sys.getsizeof(a.__dict__), sys.getsizeof(b))print(type(PointSlots.__dict__["x"]).__name__)print(hasattr(b, "__dict__"))try: b.z = 3except AttributeError as e: print("AttributeError:", e)
Output
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_property does 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.

Put it in order4 steps

Python reads obj.name on an instance. Order the places it checks, first to last.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

Key terms
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 as self.
__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.