Python › Magic Methods & Operator Overloading

How do you implement custom attribute access with __getattr__ versus __getattribute__?

Intermediate

Answer

__getattr__(self, name) is only called as a fallback when normal attribute lookup fails (attribute not found through __dict__ or the class hierarchy) -- ideal for lazy attributes or proxies. __getattribute__(self, name) is called for every attribute access unconditionally, making it more powerful but riskier (easy to cause infinite recursion) since you must carefully delegate to super().__getattribute__() for normal attributes.
class LazyConfig:
    def __getattr__(self, name):
        print(f'Loading {name} on demand')
        value = load_from_disk(name)
        setattr(self, name, value)  # cache it
        return value

config = LazyConfig()
print(config.database_url)  # triggers lazy load only once
Real-world example A configuration object lazily fetches and caches settings from a remote service only when first accessed, using __getattr__ to avoid an expensive upfront load of every possible setting.

Common follow-ups: Why is __getattribute__ more dangerous to override than __getattr__?;How does this relate to descriptors?