Python getattr()

Python’s built-in getattr(object, string) function returns the value of the object‘s attribute with name string. If this doesn’t exist, it returns the value provided as an optional third default argument. If that doesn’t exist either, it raises an AttributeError. An example is getattr(porsche, 'speed') which is equivalent to porsche.speed.

How to get an attribute with getattr() in Python - Illustrated Guide

Usage

Learn by example! Here’s an example on how to use the getattr() built-in function.

# Define class with one attribute
class Car:
    def __init__(self, brand, speed):
        self.brand = brand
        self.speed = speed


# Create object
porsche = Car('porsche', 100)
tesla = Car('tesla', 110)

# Two alternatives to get instance attributes:
print(getattr(porsche, 'brand') + " " + str(getattr(porsche, 'speed')))
print(tesla.brand + " " + str(tesla.speed))


# Get an attribute that doesn't exist with default argument:
print(getattr(porsche, 'color', 'red'))

The output of this code snippet is:

porsche 100
tesla 110
red

Syntax getattr()

The getattr() object has the following syntax:

Syntax: 
getattr(object, attribute[, default])         # Get object's attribute value or default if non-existent
ArgumentsobjectThe object from which the attribute value should be drawn.
attributeThe attribute name as a string.
defaultThe return value in case the attribute doesn’t exist.
Return ValueobjectReturns the value of the attribute of instance object or default if non-existent.

Video getattr()

Return value from getattr()

The getattr(object, attribute, default) method returns one of the following:

  • the value of the object‘s attribute
  • default, if the attribute doesn’t exist
  • AttributeError if neither the attribute exists, nor default is provided.

Interactive Shell Exercise: Understanding getattr()

Consider the following interactive code:

Exercise: Fix the error in the code!


But before we move on, I’m excited to present you my brand-new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Link: https://nostarch.com/pythononeliners


Why Using getattr() Instead of Dot to Get an Attribute?

You’ve seen two alternatives to get an attribute:

  • getattr(object, attribute_str)
  • object.attribute

Why using the getattr() function over the more concise dot syntax?

There are two main reasons:

  • getattr() provides a default value in case the attribute doesn’t exist whereas the dot syntax throws an error.
  • getattr() allows to dynamically access the attribute with the string instead of the name. For example, you may obtain the string as a user input, in which case, you cannot use the dot syntax object.attribute because attribute is a string, not a name.

Related Functions

  • The getattr() function returns the value of an attribute.
  • The setattr() function changes the value of an attribute.
  • The hasattr() function checks if an attribute exists.
  • The delattr() function deletes an existing attribute.

Summary

Python’s built-in getattr(object, string) function returns the value of the object‘s attribute with name string.

# Define class with one attribute
class Car:
    def __init__(self, brand, speed):
        self.brand = brand
        self.speed = speed


porsche = Car('porsche', 100)
print(getattr(porsche, 'brand') + " " + str(getattr(porsche, 'speed')))
# porsche 100

If this doesn’t exist, it returns the value provided as an optional third default argument.

print(getattr(porsche, 'color', 'red'))
# red

If that doesn’t exist either, it raises an AttributeError.

print(getattr(porsche, 'color'))
'''
Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\Finxter\Blog\HowToConvertBooleanToStringPython\code.py", line 12, in <module>
    print(getattr(porsche, 'color'))
AttributeError: 'Car' object has no attribute 'color'
'''

An example is getattr(porsche, 'speed') which is equivalent to porsche.speed.

print(getattr(porsche, 'speed'))
print(porsche.speed)
# Both print attribute value: 100

I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:

Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!