Categories
attributes python

How to know if an object has an attribute in Python

2214

How do I determine if an object has some attribute? For example:

>>> a = SomeClass()
>>> 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?

2

  • When you say “tell if a has the attribute property before using it?” do you want a function returning a boolean (like hasattr() returns) or is it ok to throw an AttributeError exception?

    – smci

    Feb 28 at 4:04


  • 1

    Also, don’t actually name your attribute ‘property’ , because Python has property decorator and builtin too, and those are slightly different than normal attributes/methods.

    – smci

    Feb 28 at 4:07

3122

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.

5

  • 25

    Seems to be working for checking for functions in namespace as well, e.g.: import string hasattr(string, "lower")

    – riviera

    Apr 8, 2011 at 12:54


  • 21

    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 3:04

  • 10

    @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 7:44

  • 1

    hasattr does not work if your object is a ‘dict’. Use in operator or haskey method in those cases.

    Apr 4, 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

    – alper

    Sep 14, 2021 at 3:51


779

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()

6

  • 323

    But how do you check that it was the a.property that caused AttributeError, and not something in doStuff()? It seems you don’t. I think it is really easier to ask for forgiveness, but many times, it’s also incorrect.

    – jpalecek

    Apr 14, 2009 at 13:22

  • 352

    EAFP seems … insane. HasAttr telegraphs to future maintance programmers that you are checking for a particular attribute. Getting an exception tells future programmers nothing and could lead someone down the rabbit hole.

    Oct 14, 2010 at 18:54

  • 83

    @e5: you have a fair point in this case, but in many cases EAFP is the only correct option. For example, if you check the existence of a file and then open it, expecting that it will definitely exist, your code is incorrect: the file may be deleted or renamed between the check and the use. This is called a TOCTOU error (Time-Of-Check-To-Time-Of-Use) and besides causing crashes can also be a source of security vulnerabilities.

    – Max

    Jun 1, 2011 at 13:08

  • 21

    @EthanHeilman it’s only insane when there is ambiguity in the source of the exception, which can be avoided with good design in most cases. Well-layered structuring of logic within try / except / finally generally makes for more robust (less programmer error prone) logic than littering the code with preemptive if-checks for each piece of consuming code. Makes errors very explicit also, and allows consuming programmers the option of dealing with them directly.

    Jan 2, 2013 at 16:23

  • 74

    Most of the ambiguity complaints here are simply because the sample code is poorly structured. The only thing inside the try: should be the attempted attribute access; there’s no reason to wrap the execution of doStuff as well. There still is some potential for ambiguity though: if property is a computed property instead of a plain attribute, its implementation could raise AttributeError internally. This is why in almost all real situations like this, getattr is preferable to either hasattr or catching AttributeError.

    Sep 24, 2013 at 20:21

615

You can use hasattr() or catch AttributeError, but if you really just want the value of the attribute with a default if it isn’t there, the best option is just to use getattr():

getattr(a, 'property', 'default value')

4

  • 17

    This solves both aforementioned problems: a) The ambiguity of the source of a possible AttributeError, b) Preserving the EAFP approach.

    Jan 2, 2013 at 16:17

  • 7

    It’s also 25% of the lines of code. Surely this has to be the best solution.

    – fatuhoku

    Sep 24, 2013 at 11:36

  • 22

    This is the best solution “if you really just want the value of the attribute with a default.” Although I believe this is what many people actually want when they say they want to detect whether an attribute is present, the OP actually asked for the latter, so it’s reasonable for the direct answers to that question (hasattr, AttributeError) to be listed higher.

    Dec 1, 2015 at 5:48

  • Upvoted for mentioning “default property”. There have been times I needed this, but forgot about it!

    Jun 24, 2021 at 11:56