Python getattr()

Python getattr() function is a powerful tool for dynamically accessing object attributes and methods. It allows you to retrieve attribute values, handle missing attributes gracefully, and call methods dynamically. By understanding how getattr() works, you can write more flexible and dynamic Python code.
Table of Contents

Understanding Python getattr() Function

Python getattr() is a built-in function that allows you to get the value of an object’s attribute using the attribute’s name as a string. It’s particularly useful when you don’t know the name of the attribute at the time you’re writing the code, but you’ll know it at runtime. Python getattr() takes three arguments: the object you’re interested in, the name of the attribute (as a string), and an optional default value to return if the attribute is not found. This function provides a flexible way to access attributes dynamically.

Syntax of Python getattr()

attribute_value = getattr(object, attribute_name, default_value)

Explanation

  • attribute_value: Variable will store the value of the attribute returned by getattr().
  • getattr(): Built-in function used to get the value of an attribute.
  • object: Object whose attribute value you want to retrieve. It is passed as first parameter to getattr().
  • attribute_name: String representing the name of the attribute. It is passed as second parameter to getattr().
  • default_value (optional): Value to return if the attribute is not found. It is passed as third parameter to getattr().

Example of Python getattr()

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

person = Person("Alice", 30)
age = getattr(person, "age")
print(age)

Explanation

  • class Person:: Defines a class named Person.
  • def __init__(self, name, age):: Constructor for Person.
  • self.name = name: Initializes the name attribute.
  • self.age = age: Initializes the age attribute.
  • person = Person("Alice", 30): Creates a Person object.
  • age = getattr(person, "age"): Retrieves the value of the age attribute using its name as a string and stores it into age.
  • print(age): Prints the value of age.

Output

30


getattr() Parameters

Python getattr() function accepts three parameters: object, attribute_name, and an optional default_value. The object is the object whose attribute you want to access. The attribute_name is a string that specifies the name of the attribute. The default_value is what getattr() will return if the specified attribute is not found in the object; if you don’t provide a default_value and the attribute is not found, getattr() raises an AttributeError.

Syntax

value = getattr(object, attribute_name, default_value)

Example

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

dog = Dog("Buddy")
breed = getattr(dog, "breed", "Unknown")
print(breed)

Explanation

  • class Dog:: Defines a class named Dog.
  • def __init__(self, name):: Constructor for Dog.
  • self.name = name: Initializes the name attribute.
  • dog = Dog("Buddy"): Creates a Dog object.
  • breed = getattr(dog, "breed", "Unknown"): Tries to get the breed attribute, returning “Unknown” if it doesn’t exist and stores it into breed.
  • print(breed): Prints the value of breed.

Output

Unknown


getattr() Return Value

Python getattr() function returns the value of the specified attribute from the given object. If the attribute exists in the object, getattr() returns its value. If the attribute does not exist, and you’ve provided a default_value, getattr() returns that default value. If the attribute doesn’t exist and you haven’t provided a default value, getattr() raises an AttributeError. The return type of getattr() depends on the type of the attribute being accessed.

Example

class Car:
    def __init__(self, model):
        self.model = model

car = Car("Tesla Model S")
model = getattr(car, "model")
print(model)

Explanation

  • class Car:: Defines a class named Car.
  • def __init__(self, model):: Constructor for Car.
  • self.model = model: Initializes the model attribute.
  • car = Car("Tesla Model S"): Creates a Car object.
  • model = getattr(car, "model"): Retrieves the value of the model attribute using its name as a string and stores it into model.
  • print(model): Prints the value of model.

Output

Tesla Model S


getattr() When Named Attribute is not Found

If you use Python getattr() to access an attribute that doesn’t exist in the object and you haven’t provided a default value, Python will raise an AttributeError. This exception indicates that the object has no attribute with the specified name. To avoid this error, you can either provide a default value as the third argument to getattr() or handle the AttributeError using a try-except block.

Syntax

try:
    attribute_value = getattr(object, attribute_name)
except AttributeError:
    # Handle the error

Explanation

  • try:: Block attempts to execute the getattr() function.
  • attribute_value = getattr(object, attribute_name): Tries to get the value of attribute_name from object.
  • except AttributeError:: Block catches the AttributeError if it occurs.
  • # Handle the error: Where you write code to handle the situation where the attribute is not found.

Example

class MyClass:
    def __init__(self):
        self.x = 10

obj = MyClass()
try:
    y = getattr(obj, "y")
    print(y)
except AttributeError:
    print("Attribute y not found")

Explanation

  • class MyClass:: Defines a class named MyClass.
  • def __init__(self):: Constructor for MyClass.
  • self.x = 10: Initializes the x attribute.
  • obj = MyClass(): Creates an instance of MyClass.
  • try:: This block attempts to get the value of a non-existent attribute.
  • y = getattr(obj, "y"): Tries to retrieve the value of y, which doesn’t exist.
  • print(y): This line would print the value of y if it were found.
  • except AttributeError:: Catches the AttributeError.
  • print("Attribute y not found"): Prints an error message.

Output

Attribute y not found


getattr() with Dynamic Attribute Names

One of the most powerful uses of Python getattr() is accessing attributes with dynamically determined names. You can construct the attribute’s name as a string at runtime rather than hardcoding it. This is particularly useful when working with objects whose attributes might vary based on user input, data from a file, or other runtime conditions.

Syntax

attribute_name = “some_attribute”
value = getattr(object, attribute_name)

Explanation

  • attribute_name: String variable that holds the name of the attribute you want to access.
  • value: Variable will store the value of the dynamically accessed attribute.
  • getattr(): Function retrieves the attribute’s value.
  • object: Object you’re working with. It is passed as first parameter to getattr().
  • attribute_name: Dynamically determined attribute name. It is passed as second parameter to getattr().

Example

class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

my_dog = Dog("Max", "Labrador")
attribute_name = "breed"
breed_value = getattr(my_dog, attribute_name)
print(breed_value)

Explanation

  • class Dog:: Defines a class named Dog.
  • def __init__(self, name, breed):: Constructor for Dog.
  • self.name = name: Initializes the name attribute.
  • self.breed = breed: Initializes the breed attribute.
  • my_dog = Dog("Max", "Labrador"): Creates a Dog object.
  • attribute_name = "breed": Sets attribute_name to the string “breed”.
  • breed_value = getattr(my_dog, attribute_name): Retrieves the value of the attribute named in attribute_name and stores it in breed_value.
  • print(breed_value): Prints the value of the dynamically accessed attribute.

Output

Labrador


Python getattr() Function Call

You can use Python getattr() to get a reference to a method (function) of an object and then call that method. This is useful when you don’t know which method to call at compile time, but you’ll determine it at runtime. After retrieving the method using getattr(), you can call it just like you would normally, using parentheses () and passing any required arguments.

Syntax

method = getattr(object, method_name)
result = method(arguments)

Explanation

  • method: Variable will store a reference to the method.
  • getattr(): Function retrieves the method from the object.
  • object: Object whose method you want to call. It is passed as first parameter to getattr().
  • method_name: String representing the name of the method. It is passed as second parameter to getattr().
  • result: Variable will store the result of calling the method.
  • method(arguments): Calls the retrieved method with the provided arguments.

Example

class Calculator:
    def add(self, x, y):
        return x + y

    def subtract(self, x, y):
        return x - y

calc = Calculator()
operation = "add"
method = getattr(calc, operation)
result = method(5, 3)
print(result)

Explanation

  • class Calculator:: Defines a class named Calculator.
  • def add(self, x, y):: Defines an add method.
  • return x + y: Returns the sum of x and y.
  • def subtract(self, x, y):: Defines a subtract method.
  • return x - y: Returns the difference between x and y.
  • calc = Calculator(): Creates a Calculator object.
  • operation = "add": Sets operation to the string “add”.
  • method = getattr(calc, operation): Retrieves the method named in operation (which is “add”) from calc and stores it in method.
  • result = method(5, 3): Calls the retrieved method with arguments 5 and 3.
  • print(result): Prints the result of the method call.

Output

8


Conclusion

Python getattr() is a handy function for dynamically accessing object attributes, including methods. It allows you to retrieve an attribute’s value using its name as a string, which can be determined at runtime. Python getattr also provides a way to specify a default value to return if the attribute is not found, or you can handle the AttributeError yourself. This makes getattr() particularly useful for creating flexible code that can adapt to different objects and situations without knowing their exact structure beforehand.


Also Read

Python frozenset()

Python globals()


Python Reference

python getattr()

Table of Contents