• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / Python / Python Check if Attribute Exists in Object with hasattr() Function

Python Check if Attribute Exists in Object with hasattr() Function

February 10, 2022 Leave a Comment

Using Python, the easiest way to check if an attribute exists in an object is to use the Python hasattr() function.

if hasattr(obj, "lower"):
    print("Object has attribute lower!")
else:
    print("Object doesn't have attribute lower!")

We can also use exception handling to see if an attribute exists in an object in Python.

try:
    obj.lower()
    print("Object has attribute lower!")
except TypeError:
    print("Object doesn't have attribute lower!")

When working with objects in Python, it is useful to be able to easily check if an object has a certain attribute or not.

We can check if an object has an attribute with the Python hasattr() function. The hasattr() function will return if the attribute exists or not.

Below are some examples of using the hasattr() function to check if different attributes exist.

print(hasattr("string","lower"))
print(hasattr(10,"lower"))
print(hasattr([1,2,3],"__iter__"))
print(hasattr({ "key1":"value1" },"upper"))

#Output:
True
False
True
False

Checking if an Attribute Exists with Exception Handling in Python

Another way you can check if an attribute exists with exception handling in Python.

When we try to access an attribute and the attribute doesn’t exist, we will get an AttributeError. If we don’t get an AttributeError, we will know the attribute exists.

Therefore, using this logic, we can check if an attribute exists in an object.

Below is an example in Python of checking if different attributes exist using exception handling.

try:
    0.upper()
    print('Object has attribute "upper"!')
except TypeError:
    print('Object doesn't have attribute "upper"!')

try:
    "power".upper()
    print('Object has attribute "upper"!')
except TypeError:
    print('Object doesn't have attribute "upper"!')

Object doesn't have attribute "upper"!
Object has attribute "upper"!

Hopefully this article has been useful for you to learn how to check if an object has an attribute or not in Python.

Other Articles You'll Also Like:

  • 1.  Check if Variable is Float in Python
  • 2.  Python dirname – Get Directory Name of Path using os.path.dirname()
  • 3.  Why Dictionaries Can’t Have Duplicate Keys in Python
  • 4.  Using Selenium to Get Text from Element in Python
  • 5.  Convert First Letter of String to Lowercase in Python
  • 6.  How to Count Vowels in a String Using Python
  • 7.  Python Get Number of Cores Using os cpu_count() Function
  • 8.  pandas str replace – Replace Text in Dataframe with Regex Patterns
  • 9.  Read Last N Lines of File in Python
  • 10.  Keep Every Nth Element in List in Python

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy