Intercept Attribute Access without Recursion
Core idea
An interception hook changes behavior across attribute accesses. In setattr, delegate with object.setattr(self, name, value) or a cooperative super call; writing self.name inside the hook re-enters it. Delegate reads similarly when overriding getattribute. Prefer a property or descriptor if only a few fields require validation. Special-method lookup by operators can bypass instance attribute hooks, so interception is not a security boundary.
class Gauge: def __setattr__(self, name, value): if name == 'level' and not 0 <= value <= 100: raise ValueError('outside range') object.__setattr__(self, name, value)g = Gauge()g.level = 40try: g.level = 120except ValueError: print(g.level)g.unit = '%'print(g.unit)Validation happens before delegated assignment, so a failed update leaves the value intact.
Observe special-method lookup
class Batch: def __len__(self): return 3 def __getattribute__(self, name): print('read', name) return object.__getattribute__(self, name)b = Batch()print(len(b))print(b.__len__())len uses implicit special-method lookup on the type; explicit attribute access invokes the hook.
Common mistake
Never read self.dict inside an overridden getattribute without delegation: that read can recursively invoke the same hook. Do not silently catch all exceptions.
Practice
Add a delattr hook that refuses deletion of level but delegates other deletions. Test both branches and inspect the preserved level.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Attribute interception
Check your understanding of attribute interception.
What is printed?
class C: def __setattr__(self,n,v): object.__setattr__(self,n,v*2)c=C(); c.x=4print(c.x)What is printed?
class C: def __len__(self): return 2c=C(); c.__len__=lambda: 7print(len(c),c.__len__())Which implementation avoids re-entering the same __setattr__ override?
What is a simpler tool for one validated field?