Skip to content

Python getattr() Function

How to use Python's getattr() to dynamically access object attributes, handle missing attributes with default values, and call methods safely without raising errors.

The getattr() method returns the value of the named attribute of an object. If not found, it returns the default value provided to the function.

Syntax

getattr(object, attribute, default)

getattr() Parameters

Python getattr() function parameters:

Parameter Condition Description
object Required Object whose named attribute's value is to be returned
attribute Required String that contains the attribute's name
default Optional Value that is returned when the named attribute is not found

getattr() Return Value

Python getattr() function returns

  • value of the named attribute of the given object
  • default, if no named attribute is found
  • AttributeError exception, if named attribute is not found and default is not defined

Examples

Example 1: Basic usage of getattr() function

class Person:
    age =  25
    name = "Tom"

person = Person()
print('The age is:', getattr(person, "age"))
print('The name is:', getattr(person, "name"))

output

The age is: 25
The name is: Tom

Example 2: getattr() when named attribute is not found (with and without default value)

class Person:
    age = 25
    name = "Tom"

person = Person()

print('The sex is:', getattr(person, 'sex', 'Male'))

print('The sex is:', getattr(person, 'sex'))

output

The sex is: Male
Traceback (most recent call last):
  File "main.py", line 11, in <module>
    print('The sex is:', getattr(person, 'sex'))
AttributeError: 'Person' object has no attribute 'sex'

Example 3: Using getattr() to Call Methods

class MyClass:
    def __init__(self):
        pass
    def my_method(self):
        print("Method ran")

object = MyClass()
getattr(object, 'my_method')()  # Calls the method 'my_method'

output

Method ran

Example 4: Comparison of performance between getattr() and object.name

import time

class MyClass:
    name = "TutorialReference"
    age =  25

obj = MyClass()

start_getattr = time.time()
print("The name is " + getattr(obj, 'name'))
print("Time to execute getattr " + str(time.time() - start_getattr))

start_obj = time.time()
print("The name is " + obj.name)
print("Time to execute conventional method " + str(time.time() - start_obj))

output

The name is TutorialReference
Time to execute getattr 9.298324584960938e-06
The name is TutorialReference
Time to execute conventional method 2.86102294921875e-06
Navigation