Tutorial

Python getattr() Function: Syntax, Examples, and Best Practices

Master the Python getattr() function. Learn how to dynamically access object attributes, handle missing values safely, and avoid AttributeError with practical code examples.

Drake Nguyen

Founder · System Architect

3 min read
SaaS Architecture
Modern SaaS architecture requires flexibility and performance

Introduction to Python getattr()

The Python getattr() function is a built-in utility used to retrieve the value of an attribute from an object. While developers typically access attributes using dot notation (e.g., object.name), getattr() becomes essential when the attribute name is stored as a string or needs to be determined dynamically at runtime.

One of the most powerful features of getattr() is its ability to return a default value if the specified attribute is missing, allowing for safer code execution and easier error handling.

Syntax of getattr()

The syntax for the function is straightforward:

getattr(object, name[, default])
  • object: The object from which you want to retrieve the attribute.
  • name: A string containing the name of the attribute.
  • default (Optional): The value to return if the attribute is not found.

Basic Usage Example

Let's look at how to access attribute values using getattr() compared to traditional dot notation. In the example below, we define a Student class with basic attributes.

class Student:
    def __init__(self):
        self.student_id = "101"
        self.student_name = "Adam Lam"

student = Student()

# Accessing attributes using getattr()
print('getattr : Name of the student is =', getattr(student, "student_name"))

# Accessing attributes using traditional dot notation
print('Traditional : Name of the student is =', student.student_name)
Note: The code output would display "Adam Lam" for both print statements, confirming that both methods retrieve the same data.

Handling Missing Attributes with Default Values

A common use case for getattr() is handling scenarios where an attribute might not exist. If you try to access a non-existent attribute without a default value, Python raises an AttributeError. However, by providing a third argument, you can define a safe fallback value.

Example: Using a Default Value

In this example, we attempt to access a student_cgpa attribute that has not been defined in our class.

class Student:
    def __init__(self):
        self.student_id = "101"
        self.student_name = "Adam Lam"

student = Student()

# Using the default value option avoids an error
cgpa = getattr(student, "student_cgpa", 3.00)
print('Using default value : CGPA of the student is =', cgpa)

Example: Catching AttributeError

If you omit the default value parameter and the attribute is missing, Python will interrupt execution with an error. You can handle this using a try-except block.

# Without using default value
try:
    print('Without default value :', getattr(student, "student_cgpa"))
except AttributeError:
    print("Attribute is not found :(")

The output of the logic above demonstrates the safety of the default parameter:

Using default value : CGPA of the student is = 3.0
Attribute is not found :(

Why Use getattr()?

You might wonder why you should use getattr() when dot notation is more concise. Here are the primary scenarios where this function is indispensable:

  • Dynamic Access: It allows you to access attributes when the attribute name is known only at runtime (e.g., coming from user input, a database, or a configuration file).
  • Data Completion: When processing incomplete objects, you can use the default value parameter to fill in gaps without writing verbose if-else or try-except blocks.
  • Code Flexibility: If you are working with a class that is currently under development ("work in progress"), you can use getattr() to ensure your code continues to run even if certain attributes haven't been implemented yet. Once the class is updated, the function will automatically retrieve the real value instead of the default.

For more technical details, refer to the Official Python Documentation.

Stay updated with Netalith

Get coding resources, product updates, and special offers directly in your inbox.