getattr() Function in Python

Python getattr() Function

The getattr() function in Python is a built-in function that allows you to retrieve the value of an attribute from an object dynamically. It takes three arguments: the object from which to retrieve the attribute, the name of the attribute as a string, and an optional default value to return if the attribute does not exist.

The general syntax of the getattr() function is as follows:

getattr(object, name, default)

Here's an explanation of each argument:

  • object: This is the object from which you want to retrieve the attribute.
  • name: This is the name of the attribute you want to retrieve as a string.
  • default (optional): If provided, this value will be returned if the attribute does not exist. If not provided and the attribute is not found, getattr() will raise an AttributeError.

Here's an example that demonstrates how to use getattr():

class Person:
    def __init__(self, name):
        self.name = name

person = Person("John")

# Retrieving the 'name' attribute using getattr()
name = getattr(person, 'name')
print(name)  # Output: John

# Retrieving a non-existing attribute with default value
age = getattr(person, 'age', 30)
print(age)  # Output: 30 (default value)

# Retrieving a non-existing attribute without default value
city = getattr(person, 'city')  # Raises AttributeError

In the example above, we create a Person class with a name attribute. We then create an instance of the Person class named person. Using getattr(), we retrieve the value of the name attribute, which is "John".

Next, we demonstrate using getattr() with a non-existing attribute. When the attribute 'age' does not exist, we provide a default value of 30, which is returned. However, when we try to retrieve the non-existing attribute 'city' without providing a default value, an AttributeError is raised.

The getattr() function is particularly useful when you need to access attributes dynamically or when you're working with code that needs to handle different objects with potentially different sets of attributes.