Change language

Python | hasattr () method

|

hasattr () — it is a built-in utility function in Python that is used in many day-to-day software applications. 
His main task is — check if the object has the given named attribute and return true if present, false otherwise.

Syntax: hasattr (obj, key)

Parameters:
obj: The object whose which attribute has to be checked.
key: Attribute which needs to be checked.

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

Code # 1: Demonstration of hasattr () work

# Python code for demonstration
# hasattr () works

  
# class declaration

class GfG:

  name = " Python.Engineering "

  age = 24

 
# object initialization

obj = GfG ()

 
# using hasattr () to check the name

print ( "Does name exist? " + str ( hasattr (obj, ’ name’ )))

 
# using hasattr () to check the motto

print ( "Does motto exist?" + str ( hasattr (obj, ’motto’ )))

Exit:

 Does name exist? True Does motto exist? False 

Code # 2 : Performance Analysis

< code class = "comments"> # Python code for demo
# hasattr () performance analysis

import time 

  
# class declaration

class GfG:

name = "Python.Engineering "

  age = 24

 
# object initialization

obj = GfG ()

 
# using hasattr to check if visa

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 try / in addition to check the 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))

Exit:

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

Result: normal try / throw takes less time than hasattr (), but for code readability, hasattr () is always the best choice.

Applications: this function can be used to validate keys to avoid unnecessary errors when accessing missing keys. The hasattr () chaining is sometimes used to avoid entering one related attribute when there is no other.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically