Python hasattr()

Python’s built-in hasattr(object, string) function takes an object and a string as an input. It returns True if one of the object‘s attributes has the name given by the string. Otherwise, it returns False.

Python hasattr()

Usage

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

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


# Create object
porsche = Car('porsche')

# Check if porsche has attributes
print('Porsche has attribute "brand": ', hasattr(porsche, 'brand'))
print('Porsche has attribute "color": ', hasattr(porsche, 'color'))

The output of this code snippet is:

Porsche has attribute "brand":  True
Porsche has attribute "color":  False

It has the attribute “brand” but not the attribute “color”.

Video hasattr()

Syntax hasattr()

The hasattr() object has the following syntax:

Syntax: 
hasattr(object, attribute)         # Does the object have this attribute?
ArgumentsobjectThe object from which the attribute value should be drawn.
attributeThe attribute name as a string.
Return ValueobjectReturns Boolean whether the attribute string is the name of one of the object‘s attributes.

Return value from hasattr()

The hasattr(object, attribute) method returns True, if the object has the attribute and False otherwise.

Interactive Shell Exercise: Understanding hasattr()

Consider the following interactive code:

Exercise: Fix the code so that both results of hasattr() return True!


But before we move on, I’m excited to present you my 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


Applications hasattr()

  • You can use hasattr() to avoid accessing errors when trying to access an attribute of a dynamic object.
  • You can use hasattr() in a ternary operator to conditionally assign a value to a variable such as in: age = object.age if hasattr(object, 'age') else 0
  • However, be careful when using hasattr() as it always return False, no matter the error message. Thus, it may overshadow an error different to the error that appears if the attribute doesn’t exist. So, the attribute may indeed exist but if trying to access it causes an error, the result will be False.

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 hasattr(object, string) function takes an object and a string as an input.

  • It returns True if one of the object‘s attributes has the name given by string.
  • It returns False otherwise if one of the object‘s attributes doesn’t have the name given by string.
>>> hasattr('hello', 'count')
True
>>> hasattr('hello', 'xxx')
False

Note that hasattr() also returns True if the string is the name of a method rather than an attribute.


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!