Programming
python attributes
Updated Mon, 30 May 2022 23:10:24 GMT

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?




Solution

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.





Comments (5)

  • +0 – Seems to be working for checking for functions in namespace as well, e.g.: import string hasattr(string, "lower") — Apr 08, 2011 at 12:54  
  • +0hasattr 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  
  • +0 – @JeffTratner: 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  
  • +1 – hasattr does not work if your object is a 'dict'. Use in operator or haskey method in those cases. — Apr 04, 2021 at 12:13  
  • +1 – can it be done for attribute for self? like if not hasattr(self, 'property') inside the __init__() of the object creation — Sep 14, 2021 at 03:51