Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if an object has an attribute in Python

Is there a way in Python to determine if an object has some attribute? For example:

>>> a = SomeClass() >>> a.someProperty = value >>> a.property Traceback (most recent call last):   File "<stdin>", line 1, in <module> AttributeError: SomeClass instance has no attribute 'property' 

How can you tell if a has the attribute property before using it?

like image 373
Lucas Gabriel Sánchez Avatar asked Mar 04 '09 14:03

Lucas Gabriel Sánchez


People also ask

How do you check if an object has an attribute Python?

We can use hasattr() function to find if a python object obj has a certain attribute or property. hasattr(obj, 'attribute'): The convention in python is that, if the property is likely to be there, simply call it and catch it with a try/except block.

How do you check if an object has a certain attribute?

If you want to determine whether a given object has a particular attribute then hasattr() method is what you are looking for. The method accepts two arguments, the object and the attribute in string format.

Does Python object have attributes?

Since everything in Python is an object and objects have attributes (fields and methods), it's natural to write programs that can inspect what kind of attributes an object has. For example, a Python program could open a socket on the server and it accepts Python scripts sent over the network from a client machine.

Which method is used to check if an attribute exists or not in Python?

The hasattr() method returns true if an object has the given named attribute and false if it does not.


2 Answers

Try hasattr():

if hasattr(a, 'property'):     a.property 

See zweiterlinde's answer below, who offers good advice about asking forgiveness! A very pythonic approach!

The general practice in python is that, if the property is likely to be there most of the time, simply call it and either let the exception propagate, or trap it with a try/except block. This will likely be faster than hasattr. If the property is likely to not be there most of the time, or you're not sure, using hasattr will probably be faster than repeatedly falling into an exception block.

like image 191
Jarret Hardie Avatar answered Sep 28 '22 23:09

Jarret Hardie


As Jarret Hardie answered, hasattr will do the trick. I would like to add, though, that many in the Python community recommend a strategy of "easier to ask for forgiveness than permission" (EAFP) rather than "look before you leap" (LBYL). See these references:

EAFP vs LBYL (was Re: A little disappointed so far)
EAFP vs. LBYL @Code Like a Pythonista: Idiomatic Python

ie:

try:     doStuff(a.property) except AttributeError:     otherStuff() 

... is preferred to:

if hasattr(a, 'property'):     doStuff(a.property) else:     otherStuff() 
like image 33
zweiterlinde Avatar answered Sep 28 '22 23:09

zweiterlinde