liveBook · Manning

__getattr__

As explained in Python How-To

__getattr__ is a Python special method invoked to provide an instance attribute value when ordinary attribute lookup cannot find that attribute.

__getattr__ provides an instance attribute when ordinary lookup cannot find that name. Python first checks the instance’s __dict__; if the name is absent, __getattr__ runs as a fallback. section 9.4.2

Load profile data only when requested

A User class can fetch profile_data lazily. __getattr__ performs the expensive operation only on the first access, stores the result with setattr, and returns the cached value on later accesses. The first request prints '__getattr__ called for profile_data' and '*** Run the expensive operation'; the second returns the same data without repeating the operation. section 9.4.2

Do not initialize the lazy attribute in __init__, even with None, because storing the name in __dict__ prevents __getattr__ from being called. For lazy attributes, properties are usually clearer and more explicit. section 9.4.2 section 9.4.4

How Python How-To covers it

How deep it goes
Explains fallback lookup through __dict__, lazy loading, caching, and the property trade-off, while noting that resolution is simplified.
Examples
Demonstrates a User object fetching and caching profile data only when profile_data is first accessed.
What it assumes
Assumes custom classes and instance attributes, while explaining __dict__ lookup and fallback behavior.
What you can do after
Build it from scratch by overriding __getattr__ to fetch and cache an expensive attribute on demand.
How it connects
Connects __dict__, attribute resolution, lazy attributes, properties, and custom classes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.