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?
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.
import string hasattr(string, "lower")
— Apr 08, 2011 at 12:54 hasattr
is exactly the same as using try
/except AttributeError
: the docstring of hasattr (in Python 2.7) says that it uses getattr hand catches exceptions. — Apr 27, 2012 at 03:04 hasattr
is unfortunately not exactly the same as a try: ... except AttributeError:
in Python 2.x since hasattr
will catch all exception. Please see my answer for an example and a simple workaround. — Apr 24, 2013 at 07:44 self
? like if not hasattr(self, 'property')
inside the __init__()
of the object creation — Sep 14, 2021 at 03:51 External links referenced by this document: