getAttr
getattr is a built-in function in Python that retrieves the value of an attribute from an object using the attribute's name as a string. It takes two required arguments, the object and the attribute name, and an optional third argument, default, which is returned if the attribute is not found. If the attribute exists, its value is returned; if it does not exist and a default is provided, the default value is returned; otherwise an AttributeError is raised.
Attribute lookup performed by getattr follows Python’s normal attribute access rules. This means that __getattribute__ and,
Common uses of getattr include dynamic access to attributes when the attribute name is determined at runtime,
- getattr(obj, 'attr') returns obj.attr if it exists.
- getattr(obj, 'attr', default) returns default when obj has no attribute named 'attr'.
- getattr(module, 'name') can access module attributes programmatically, without hardcoding the name.
getattr is a fundamental tool for dynamic attribute access in Python and is widely used in libraries