In this article we will explore how to use the Python getattr() function.

Table of Contents


Introduction

Python getattr() function is a built-in function that allows to dynamically access attributes of an object. Specifically, it is used to retrieve names attributes of Python objects.


The syntax of the Python getattr() function is:

getattr(object, name[, default])

where:

  • object – Python object from which we want to retrieve an attribute
  • name – name of the named attribute of a Python object
  • default – optional parameter to specify the return value if the named attribute is not found. If it’s not specified, the code will return an AttributeError

The getattr() function, when called, searches for a specified named attribute of a given Python object and returns its value.

In the following sections we will explore some of the common use cases for getattr() function.


Accessing attributes of objects dynamically using getattr()

One of the most popular use cases for the Python getattr() function is accessing attributes of an object dynamically.

Let’s start by creating a new Python object Car that has three attributes (make, model, price):


class Car:

    def __init__(self, make, model, price):

        self.make = make
        self.model = model
        self.price = price

Next, we will create an instance of this class with some sample values:


car = Car('Audi', 'Q7', 100000)

Now we can use getattr() function to access attributes of this class dynamically.

For example, let’s say we want to retrieve the price attribute for the car object we just created:


attr_name = 'price'

attr_value = getattr(car, attr_name)

print(attr_value)

and you should get:

100000

In case you try to retrieve the attribute that the object doesn’t have, you will see an AttributeError.

For example, this object has no attribute colour, so let’s see what happens when we try to retrieve it:


attr_name = 'colour'

attr_value = getattr(car, attr_name)

print(attr_value)

and you should get:

AttributeError: 'Car' object has no attribute 'colour'

This approach is very useful if you are working with multiple classes where you don’t know whether they necessarily have the attributes you are looking for, and it can save a lot of time and code amount to quickly run these tests to retrieve attributes’ values.


Building Dynamic APIs using getattr()

Another use cases for the Python getattr() function is building dynamic APIs in Python.

Let’s start by creating a simple Calculator class with a few methods that perform mathematical calculations:


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

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

Now we can build an API around this Calculator class, that will allow to call any of the methods dynamically (using Python getattr() function):


class CalculatorAPI:

    def __init__(self, calculator):

        self.calculator = calculator


    def call_method(self, method_name, *args):

        method = getattr(self.calculator, method_name, None)
        
        if method:
            return method(*args)
        else:
            return f"Method '{method_name}' not found"

Once the API is built, we can test it with different calculations like addition and subtraction and check the results:


calculator = Calculator()

api = CalculatorAPI(calculator)

print(api.call_method("add", 7, 8))
print(api.call_method("subtract", 9, 1))

and you should get:

15
8

In this example we use the Python getattr() function to dynamically access the required method of a Python class.


Loading modules dynamically using getattr()

Another use cases for the Python getattr() function is loading modules dynamically at runtime in Python.

In this example we will use a built-in Python module importlib, which is an implementation of the import statement. Specifically, we will work with import_module() function for programmatic importing.

We will use the getattr() function to access specific functions in the loaded module.

Let’s say we want to build a small program that asks the user which module to import, which function from that module to access, and what operation to perform.

For example, we want to import the math module, access the sqrt() function and find the square root of 25.

We are going to load the module and function programmatically and perform the calculation:


#Import the required dependency
import importlib

#Define module name
module_name = 'math'

#Programmatically load module
module = importlib.import_module(module_name)

#Define function name
function_name = 'sqrt'

#Programmatically load function
function = getattr(module, function_name)

#Define input for the function
num = 25

#Calculate the result
result = function(num)

#Print the result
print(f"Result: {result}")

And you should get:

5.0

While this is a very simplistic example that doesn’t look like a useful application of the sqrt() function, it illustrates the general idea of loading modules and functions dynamically.


Conclusion

In this article we explored the Python getattr() function.

Now that you know the basic functionality, you can practice using it in your projects to add more functionality to the code.

Feel free to leave comments below if you have any questions or have suggestions for some edits and check out more of my Python Functions tutorials.