Separate __getattribute__ from __getattr__
Core idea
Normal explicit instance attribute access enters getattribute. If it raises AttributeError, Python can call getattr as a fallback. Use object.getattribute(self, name) to delegate standard lookup without accidentally calling the override again. Fallbacks should raise AttributeError for names they cannot provide so getattr with a default and hasattr behave correctly.
class Item: code = 'P7' def __getattr__(self, name): if name == 'label': return 'item-' + self.code raise AttributeError(name)i = Item()print(i.code, i.label, getattr(i, 'weight', 0))print(hasattr(i, 'weight'))Existing code bypasses fallback. Only label is synthesized; weight is genuinely absent.
Trace ordinary lookup
class Probe: value = 5 def __getattribute__(self, name): print('read', name) return object.__getattribute__(self, name) def __getattr__(self, name): return 'missing:' + namep = Probe()print(p.value)print(p.other)Both reads enter the override; only the second triggers the fallback.
Common mistake
Returning None for every unknown name makes hasattr report True and hides typos. An AttributeError raised inside a descriptor can also trigger fallback, so avoid masking real implementation bugs.
Practice
Extend Item with a second explicit alias and test that a misspelled alias still raises AttributeError.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Getattribute and getattr
Check your understanding of getattribute and getattr.
What is printed?
class C: x=1 def __getattr__(self,n): return 2print(C().x,C().y)What is printed?
class C: def __getattr__(self,n): raise AttributeError(n)print(getattr(C(),'x',8))Which hook sees explicit reads of existing attributes?
What should fallback raise for an unsupported attribute?