Lesson · Python Data Model & Special Methods
Attribute Access Model
55 min readAttribute Access Model
Attribute access is programmable. `__getattribute__`, `__getattr__`, and `__setattr__` can implement proxies and dynamic objects, but they also sit on paths that are easy to recurse into accidentally.
Learning goals
- Explain the difference between
__getattribute__and__getattr__: which runs on every lookup and which only after failure. - Trace the lookup order in the worked example: instance dictionary, class attributes, then
__getattr__. - Write a
__getattr__that serves values from a backing dictionary and raisesAttributeErrorfor unknown names. - Explain why the example's
__init__writes internal state throughobject.__setattr__. - Decide when a dynamic attribute hook is warranted and when a plain method would be safer.
Mental model
The three hooks sit on one pipeline with different scopes: __getattribute__ sees every lookup, __getattr__ is the last chance after normal lookup fails, and __setattr__ sees every assignment. The worked example leaves the first and third alone and uses the middle one: settings.theme is not a real attribute, so lookup falls through to __getattr__, which reads from the internal _values dictionary.
Mental model
read it top to bottom
obj.attr → __getattribute__ (runs on every lookup) ↓ not found in the class chain or the instance dictionary __getattr__ (fallback only, after normal lookup fails) obj.attr = v → __setattr__ (runs on every assignment)
Core idea
Attribute access is a pipeline with three interception points: __getattribute__ wraps every lookup, __getattr__ fires only when normal lookup fails, and __setattr__ wraps every assignment. The worked example uses the fallback point to turn a dictionary into attribute syntax, and the detail that keeps it correct is raising AttributeError, not KeyError, when a name is unknown, because hasattr, defaulted getattr, and every inspection tool depend on that contract.
__getattr__
__getattr__ runs only after normal attribute lookup fails. It is appropriate for computed fallback attributes or proxies, but misspellings can become harder to detect if it is too permissive.
__getattribute__
__getattribute__ intercepts every instance attribute lookup. Implementations must delegate carefully, usually through object.__getattribute__, to avoid infinite recursion.
__setattr__
__setattr__ intercepts every attribute assignment: obj.attr = value calls it instead of writing straight to the instance dictionary. A class that overrides it must route its internal state through object.__setattr__ or the instance __dict__, or assignments recurse into the override. Keeping reads and writes in sync with a backing store is the usual reason to define it.
Attribute lookup
Instance attribute access consults descriptors, the instance dictionary, and class hierarchy according to specific precedence rules. Understanding that order explains properties, methods, and shadowing.
Dynamic proxies
A dynamic proxy forwards attribute access to another object, using __getattr__ (and often __setattr__) so the wrapper does not have to name every attribute in advance. Proxies fit delegation to records, remote objects, and dict-like stores while keeping one stable interface. They also hide real structure, so a proxy should answer only for names it genuinely owns and raise AttributeError for the rest.
Walkthrough
Settings.__init__stores the backing dictionary withobject.__setattr__(self, "_values", {...}); the explicit call writes the internal state directly, which is the pattern a class must keep once it overrides__setattr__itself.settings.themeis not found on the instance or the class, so normal lookup fails and__getattr__("theme")runs; it returnsself._values["theme"], printingdark.- When the key is missing, the
except KeyErrorblock raisesAttributeError(name) from exc, keeping the exception type callers andhasattrexpect while preserving the original cause on the traceback. - Predict before running: the printed line
dark, and whatsettings.missingdoes (raisesAttributeError: missing).
Experiments to try
- Add a
printinside__getattr__and readsettings.themetwice; confirm the fallback runs on every access because no real attribute is ever stored. - Access
settings.missingand inspect the traceback: note theAttributeErrorand theKeyErrorcause chained byfrom exc. - Change the handler to
raise AttributeError(name)withoutfrom exc; compare the two tracebacks and decide which failure you would rather debug. - Write
settings._values["size"] = 10and readsettings.size; then callhasattr(settings, "nope")and explain which method produced the answer.
Common mistakes
- Raising
KeyErrorfrom__getattr__:hasattrand defaultedgetattronly recognizeAttributeErroras "no such attribute", so anything else escapes as an unexpected failure. - Implementing
__getattribute__without delegating toobject.__getattribute__for the common case, so the method calls itself and ends in aRecursionError. - Using
__getattr__to answer for any name at all, which turns typos into silently wrong values and defeats autocompletion and static analysis. - Forgetting that
__getattr__does not see writes: a dynamic store that serves reads still needs__setattr__(or direct dictionary writes) beforesettings.new = 1lands anywhere.
Practice: Easy
- Run the worked example and record the printed line; then read
settings.missingand record the exact exception type and message. - Add
settings._values["size"] = 10and printsettings.size; explain which method served the value and why no real attribute exists on the instance. - Call
hasattr(settings, "theme")andhasattr(settings, "missing"); connect both answers to the exception rule inside__getattr__.
Practice: Medium
- Add
__setattr__that writes intoself._values(keeping the__init__bypass) sosettings.language = "en"can be read back assettings.language; test the round trip. - Add
__getattribute__that prints each name before delegating toobject.__getattribute__; record which reads print and explain how the order relative to__getattr__shows up in the output. - Wrap a dict in a
Frozenproxy whose__getattr__serves reads and whose__setattr__raisesAttributeError; verify reads work and writes fail with a clear message.
Practice: Hard
- Design a
Recordproxy that serves column names from an internal dictionary through__getattr__, raisesAttributeErrorfor unknown names, and exposeskeys()for introspection; test reads, misses, andhasattrbehavior. - Build a failure lab:
__getattr__raisingKeyErrorand thehasattrmisbehavior it causes;__getattribute__recursing into itself and theRecursionError;__getattr__answering every name and the typo it silently accepts. Explain each mechanism and the fix. - Connect this lesson to library code: explain how a proxy's
__getattr__interacts withgetattr(obj, name, default)and with code that checkshasattrbefore using a capability, and give one bug each convention prevents.
Lesson checklist
- I can say which hook runs on every lookup, which runs only on failure, and which handles writes.
- I can write
__getattr__that serves values from a backing dict and raisesAttributeErrorfor misses. - I can explain why
__getattr__runs again on every access tosettings.theme. - I can spot a
__getattribute__implementation that will recurse and say how to fix the delegation.
Remember
Attribute access is a pipeline: `__getattribute__` sees every lookup, `__getattr__` runs only after normal lookup fails, and `__setattr__` sees every assignment. The worked example turns a dictionary into attribute syntax through the fallback hook and keeps it correct by raising `AttributeError` on misses, which is the contract `hasattr` and defaulted `getattr` lean on.
Interview angles
What is the main purpose of **__getattr__**?+
__getattr__ runs only after normal attribute lookup fails. It is appropriate for computed fallback attributes or proxies, but misspellings can become harder to detect if it is too permissive.
What should you pay attention to when using **__getattribute__**?+
__getattribute__ intercepts every instance attribute lookup. Implementations must delegate carefully, usually through object.__getattribute__, to avoid infinite recursion.
How does **__setattr__** fit into this lesson?+
__setattr__ intercepts every attribute assignment, so obj.attr = value passes through it before anything lands on the instance. The worked example writes its internal dictionary with object.__setattr__, and a class that routes writes into a backing store implements __setattr__ to keep keys and attributes in sync.
Why must `__getattr__` raise `AttributeError` (rather than `KeyError`) for names it cannot resolve?+
AttributeError is the protocol: hasattr returns False on it and getattr(obj, name, default) falls back to the default. A KeyError escapes both checks as an unexpected failure, so duck-typing code and first-time debugging get misleading results.