concept

__getattr__

__getattr__ is a special method in Python that allows developers to define custom behavior when an attribute is accessed on an object but not found through the normal lookup process. It is part of Python's attribute access protocol, enabling dynamic attribute handling, such as lazy loading, delegation, or implementing proxy patterns. This method is called only when the attribute does not exist in the object's instance dictionary or class hierarchy.

Also known as: getattr method, custom attribute access, dynamic attribute handling, magic method getattr, Python __getattr__
🧊Why learn __getattr__?

Developers should learn __getattr__ when building flexible APIs, implementing dynamic proxies, or managing attribute access in complex object models, such as in ORMs (Object-Relational Mappers) or configuration objects. It is particularly useful for cases where attributes are computed on-the-fly, need to be fetched from external sources, or when creating wrappers that forward calls to other objects, enhancing code adaptability and reducing boilerplate.

Compare __getattr__

Learning Resources

Related Tools

Alternatives to __getattr__