The getattr()
function is used to access the value of a specified attribute from an object. It can be used as an alternative to dot notation (i.e. obj.attribute
) to access the attribute of an object.
getattr(obj, name, default = None)
obj |
The object from which to get the attribute value. |
attribute |
The name of the attribute whose value is to be retrieved. |
default |
A default value that will be returned if the attribute does not exist in object. It is optional and defaults to None . |
The function returns the value associated with the specified attribute. If the default
argument is not given and the method does not exist, an AttributeError
will be raised.
With a default value
In the above example, we try to access a non-existent attribute z , but because we had specified a default value, the function returns it instead of raising an AttributeError.
Call a method with getattr() function
Since the getattr()
function returns the actual value associated with an attribute, if the value is a method or a function, we can just call it normally. That is we place parenthesis after the returned value with any necessary arguments.
With Builtin data types
with strings
with lists
With modules
Why use getattr Function
-
Dynamic attribute access: When you need to access attributes dynamically based on user input or other runtime conditions, you can use
getattr()
to fetch the attribute value. This is possible because the getattr() function allows us to accesses an attribute using its name as a string. -
Attribute fallback: If an object has a fallback behavior for missing attributes, you can use
getattr()
to retrieve the attribute value, providing a default value if it doesn't exist. -
Dealing with optional attributes: When working with objects that may or may not have certain attributes, you can use
getattr()
to check for their existence and handle them accordingly.