Attribute Resolution: __getattr__ vs __getattribute__
`__getattr__` is a gentle fallback invoked ONLY when an attribute is missing from an instance. `__getattribute__` is an aggressive interceptor invoked on EVERY single attribute access. Accessing `self.attr` inside `__getattribute__` triggers infinite recursion without `super()` 🔄⚠️.
class LazyProxy:
def __init__(self, target):
super().__setattr__("_target", target)
def __getattribute__(self, name):
# Accessing internal fields must route via super():
if name.startswith("_"):
return super().__getattribute__(name)
target = super().__getattribute__("_target")
return getattr(target, name)
class Service:
def ping(self): return "PONG 🏓"
proxy = LazyProxy(Service())
print(proxy.ping()) # Routes through __getattribute__ seamlessly 🚀
# 83. Attribute Resolution: __getattr__ vs __getattribute__ The difference between `__getattr__` and `__getattribute__` is the difference between a safety net and a mandatory tollbooth 🛑. ```python # The Mental Model: # __getattr__(self, name): # Called ONLY after Python searched __dict__, descriptors, and class tree and FOUND NOTHING! # Perfect for dynamic fallbacks (e.g. config.UNKNOWN_KEY -> None). # __getattribute__(self, name): # Called FIRST on EVERY SINGLE DOT ACCESS, even if the attribute definitely exists! # Perfect for transparent proxies, audit interceptors, and RPC stubs. ``` ### The Infinite Recursion Trap Inside `__getattribute__(self, name)`, writing `self.target` triggers `self.__getattribute__('target')`, which triggers `self.__getattribute__('target')`, ad infinitum until CPython exhausts the stack with `RecursionError: maximum recursion depth exceeded`! Always retrieve instance attributes via: ```python super().__getattribute__(name) ``` or bypass by reading `object.__getattribute__(self, name)` directly 🔄⚠️. --- ### Interactive Pop-Quiz 🧠 #### What catastrophe happens if you write return self.target directly inside __getattribute__()? - [ ] It triggers infinite recursion and crashes the Python runtime with a RecursionError 🛑 - [ ] It deletes the attribute permanently from the class namespace - [ ] It executes the function in an isolated worker thread - [ ] It re-encodes the attribute name in hexadecimal ASCII --- ### Practical Challenge 🎯 Build `AuditWrapper` using `__getattribute__`. It holds `target` and `accessed_fields = []` (set via `super().__setattr__`). Intercept every attribute lookup (except `'target'` and `'accessed_fields'`), log the attribute name to `accessed_fields`, and return the attribute from `target`. Wrap an object with attribute `data = 42`. Access `wrapper.data`, assert `accessed_fields == ['data']`, and print the log. <details> <summary>Solution</summary> ```python class AuditWrapper: def __init__(self, target): super().__setattr__("target", target) super().__setattr__("accessed_fields", []) def __getattribute__(self, name): if name in ("target", "accessed_fields"): return super().__getattribute__(name) self.accessed_fields.append(name) return getattr(self.target, name) class DataContainer: def __init__(self): self.data = 42 wrapper = AuditWrapper(DataContainer()) val = wrapper.data assert val == 42 assert wrapper.accessed_fields == ["data"] print(wrapper.accessed_fields) ``` </details>