Attribute access is a protocol you can hook
Every time you write obj.attr or obj.attr = value in Python, the interpreter follows a lookup chain: it checks data descriptors on the type, then instance __dict__, then non-data descriptors and class attributes. Descriptors are objects implementing any of __get__, __set__, or __delete__, and they are the single mechanism behind property, classmethod, staticmethod, and most ORM field magic. Interviewers ask about descriptors because a candidate who can explain the lookup order can also explain why a property setter runs even though the instance has a matching attribute â a question that separates people who use Python daily from people who understand it.
Prerequisites
- !Instance and class attributes
- !Functions as class members, bound methods
What You'll Learn
- 1Recite the attribute lookup chain and predict which value obj.attr returns
- 2Distinguish data descriptors from non-data descriptors and their precedence
- 3Explain how property is implemented as a data descriptor
- 4Handle the obj-is-None and __set_name__ conventions correctly in custom descriptors
The four protocol methods
__get__(self, obj, objtype=None) is called when the attribute is read. __set__(self, obj, value) runs on assignment, and __delete__(self, obj) on deletion. The often-forgotten fifth method is __set_name__(self, owner, name), invoked automatically while the class body is executed, which lets the descriptor learn the attribute name it was bound to and the class that owns it. Before __set_name__ existed, descriptor authors had to pass the storage name manually to every instance; today the convention is to derive a private attribute such as _{name} inside __set_name__ and never hard-code names.
Two details trip up even experienced developers. First, __get__ receives obj=None when the attribute is accessed on the class rather than an instance â MyClass.radius instead of my_instance.radius â and the correct behavior is to return the descriptor object itself so callers can introspect it. Second, __set__ returns None by design; any attempt to use its result is a bug. Both points appear regularly in follow-up questions.
class Tracing:
"""Minimal descriptor that logs every access."""
def __set_name__(self, owner, name):
self.public_name = name
self.private_name = f"_{name}"
def __get__(self, obj, objtype=None):
if obj is None:
return self
print(f"get {self.public_name}")
return getattr(obj, self.private_name, None)
def __set__(self, obj, value):
print(f"set {self.public_name} = {value!r}")
setattr(obj, self.private_name, value)
class Point:
x = Tracing()
y = Tracing()
def __init__(self, x, y):
self.x = x # triggers __set__
self.y = y
p = Point(3, 4)
print(p.x) # logs the get
print(Point.y) # returns the Tracing instance itself
Data descriptors versus non-data descriptors
The classification is purely mechanical: a descriptor that defines __set__ or __delete__ is a data descriptor; one that defines only __get__ is a non-data descriptor. The consequence is precedence. When both a data descriptor and an instance dictionary entry exist for the same name, the data descriptor wins. When only a non-data descriptor exists, the instance dictionary entry wins â which is why assigning to obj.method silently shadows a bound method, and why caching decorators can store results on the instance to short-circuit future lookups.
This precedence rule explains several language behaviors interviewers love. property defines __set__ (even when only a getter is provided, the setter raises AttributeError), so it is a data descriptor and its getter always runs. Bound methods are non-data descriptors: the first attribute access creates a bound-method entry in the instance dictionary, making subsequent lookups faster. The famous optimization trick of storing a per-instance override in instance.__dict__[name] only works for non-data descriptors â try it on a property and you will see the property still intercepts.
| Lookup for obj.name | Winner | Reason |
|---|---|---|
| Data descriptor on type + entry in instance dict | Data descriptor | Data descriptors outrank the instance dict |
| Non-data descriptor on type + entry in instance dict | Instance dict | Instance entries shadow non-data descriptors |
| Only non-data descriptor on type | Non-data descriptor | Nothing else competes |
| Only entry in instance dict | Instance dict | Normal attribute |
| Nothing found | AttributeError | Or __getattr__ fallback if defined |
How property works internally
The built-in property object stores the getter, setter, and deleter functions and exposes them through __get__, __set__, and __delete__. The decorator syntax @prop.getter returns a new property that shares the existing setter and deleter, which is why the decorated functions must be defined in order â the getter first, then the setter referencing the property object. Reimplementing property in twenty lines is a standard interview exercise, and doing it cleanly demonstrates that you understand descriptors rather than merely using them.
The setter pattern for computed attributes is worth internalizing: store the raw value under a private name in __init__, expose derived values through read-only properties, and route any external writes back through the primary setter so every view of the data stays consistent. A temperature class that stores Celsius and exposes Fahrenheit both ways is the classic demo; a money class that stores minor units and exposes formatted strings is the production-flavored version.
class Temperature:
"""Celsius storage with a Fahrenheit view â property as descriptor."""
def __init__(self, celsius=0.0):
self._celsius = celsius
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("below absolute zero")
self._celsius = value
@property
def fahrenheit(self):
return self._celsius * 9 / 5 + 32
@fahrenheit.setter
def fahrenheit(self, value):
self.celsius = (value - 32) * 5 / 9
t = Temperature(25)
print(t.fahrenheit) # 77.0
t.fahrenheit = 32
print(t.celsius) # 0.0
Writing custom descriptors without footguns
A reusable validated-field descriptor subclasses a small base that implements __set_name__, __get__, and __set__, and leaves validation to a subclass hook. The base stores values on the instance under a private name so each object keeps its own state, while the descriptor itself lives on the class and is shared â that separation of per-class behavior and per-instance data is the entire design in one sentence.
Caching is the other flagship use. A cached-property descriptor computes on first access and writes the result into obj.__dict__[name]. Because the instance dictionary entry now exists and the descriptor can be made non-data, subsequent lookups hit the cache even before __get__ runs â though the usual implementation still defines only __get__ and checks the dictionary explicitly for clarity. A time-to-live variant stores a (value, timestamp) tuple and recomputes when the entry expires, a pattern you will recognize in configuration clients and API wrappers.
The production pitfalls are predictable: forgetting the obj is None branch breaks class-level access; hard-coding the attribute name instead of using __set_name__ breaks reuse; storing state on the descriptor instance rather than the object causes all instances to share one value; and failing to cooperate with __slots__ classes, which have no __dict__, yields confusing AttributeErrors. Mentioning any two of these unprompted marks you as someone who has shipped descriptor code rather than copied a blog post.
Slots, weak references, and testing descriptors
Descriptors interact with two lower-level features that interviewers sometimes probe. On a class that declares __slots__, there is no instance __dict__, so a descriptor that stores values with setattr(obj, self.private_name, value) still works because the slot exists on the class â but a descriptor that expects to stash arbitrary extra attributes on the instance will fail. State clearly that validated-field descriptors and slots compose fine when the private name matches a declared slot. Second, descriptors held only by the class are eligible for garbage collection with the class, but descriptors that register themselves in external registries must use weak references to avoid keeping classes alive; weakref support in a descriptor is a senior-level detail worth one sentence.
Testing a descriptor is testing a class attribute that behaves like an instance attribute: exercise both instance and class access, verify that assignment triggers __set__, and confirm that deletion either works or raises the intended error. A small parametrized test suite over a couple of fields usually reveals the obj-is-None and shared-state bugs before production does.
Common Mistakes
Omitting the obj-is-None guard in __get__
Fix: Return the descriptor itself when obj is None so class-level access works
Hard-coding the private attribute name in every descriptor
Fix: Derive it in __set_name__ from the name parameter
Keeping cached values on the descriptor object
Fix: Store them on the instance â descriptors are shared across all instances
Defining only a getter on a descriptor and expecting assignment to fail loudly
Fix: For custom descriptors, define __set__ to raise AttributeError when no setter exists
Best Practices
- Reimplement property once by hand; the twenty lines demystify the decorator forever
- Use descriptors for cross-cutting field logic â validation, caching, coercion â not for one-off behavior
- Document that descriptors are class-level and state must live on the instance
- Prefer the standard property for simple cases; save custom descriptors for patterns that repeat across many classes
Interview Questions
Q1: Explain the attribute lookup chain for instance.attr.
Python checks the type's MRO for a data descriptor; if found, it wins. Otherwise the instance __dict__ is checked. If that misses, non-data descriptors and other class attributes are consulted, and finally __getattr__ raises AttributeError if defined.
Q2: Why do properties take precedence over instance attributes?
property objects define __set__, making them data descriptors, and data descriptors outrank the instance dictionary during attribute lookup.
Q3: What is __set_name__ and when does it run?
It is called automatically with the owning class and attribute name while the class body executes, letting the descriptor discover its name without manual wiring.
Q4: Data versus non-data descriptors â why does the distinction matter?
Data descriptors win over instance dictionary entries; non-data descriptors lose to them. This affects caching strategies, method shadowing, and property behavior.
Q5: How are classmethod and staticmethod implemented?
Both are non-data descriptors. classmethod's __get__ returns a bound method that passes the class as the first argument; staticmethod's __get__ returns the underlying function unchanged.
Key Takeaways
- Descriptors hook __get__, __set__, __delete__, and __set_name__
- Data descriptors outrank instance attributes; non-data descriptors lose to them
- property is a data descriptor â that is why setters intercept assignments
- Handle obj is None in __get__ and derive storage names via __set_name__
- Keep per-instance state on the instance; the descriptor is shared class-level machinery
- Descriptors sit underneath property, classmethod, and staticmethod â one mechanism, many surfaces