A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-hasattr-method/ below:

Python hasattr() method - GeeksforGeeks

Python hasattr() method

Last Updated : 11 Jul, 2025

Python hasattr() function is an inbuilt utility function, which is used to check if an object has the given named attribute and return true if present, else false. In this article, we will see how to check if an object has an attribute in Python.

Syntax of hasattr() function

Syntax : hasattr(obj, key)

Parameters : 

Returns : Returns True, if attribute is present else returns False. 

Example 1:  Python hasattr() function example

Here we will check if an object has an attribute, to find attributes of the object in python we have demonstrated the following code.

Python3
# declaring class
class GfG:
    name = "GeeksforGeeks"
    age = 24


# initializing object
obj = GfG()

# using hasattr() to check name
print("Does name exist ? " + str(hasattr(obj, 'name')))

# using hasattr() to check motto
print("Does motto exist ? " + str(hasattr(obj, 'motto')))

Output: 

Does name exist ? True
Does motto exist ? False
Example 2: Performance analysis between hasattr() method and try statement

This is the Simple Ways to Check if an Object has Attribute in Python or not using performance analysis between hasattr() function and try statement.

Python3
import time

# declaring class
class GfG:
    name = "GeeksforGeeks"
    age = 24

# initializing object
obj = GfG()

# use of hasattr to check motto
start_hasattr = time.time()
if(hasattr(obj, 'motto')):
    print("Motto is there")
else:
    print("No Motto")

print("Time to execute hasattr : " + str(time.time() - start_hasattr))

# use of try/except to check motto
start_try = time.time()
try:
    print(obj.motto)
    print("Motto is there")
except AttributeError:
    print("No Motto")
print("Time to execute try : " + str(time.time() - start_try))

Output: 

No Motto
Time to execute hasattr : 5.245208740234375e-06
No Motto
Time to execute try : 2.6226043701171875e-06

Result: Conventional try/except takes lesser time than hasattr(), but for readability of code, hasattr() is always a better choice.

Applications: This function can be used to check keys to avoid unnecessary errors in case of accessing absent keys. Chaining of hasattr() is used sometimes to avoid entry of one associated attribute if the other is not present.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4