Rectangle 27 0

How to know if an object has an attribute in Python?


if hasattr(someObject, 'someProp'):
    #Access someProp/ set someProp
    pass
try:
    getattr(someObject, 'someProperty')         
except AttributeError:
    print "Doesn't exist"
else
    print "Exists"

I think what you are looking for is hasattr. However, I'd recommend something like this if you want to detect python properties-

The disadvantage here is that attribute errors in the properties __get__ code are also caught.

Well, not exactly, don't use the built-in IFF you want to detect properties. Otherwise hasattr is perfectly good.

Note
Rectangle 27 0

How to know if an object has an attribute in Python?


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

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

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.

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

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

Note
Rectangle 27 0

How to know if an object has an attribute in Python?


if hasattr(a, 'property'):
    doStuff(a.property)
else:
    otherStuff()
try:
    doStuff(a.property)
except AttributeError:
    otherStuff()

@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.

@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.

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:

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.

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.

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.

Note
Rectangle 27 0

How to know if an object has an attribute in Python?


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

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

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.

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

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

Note
Rectangle 27 0

How to know if an object has an attribute in Python?


if hasattr(someObject, 'someProp'):
    #Access someProp/ set someProp
    pass
try:
    getattr(someObject, 'someProperty')         
except AttributeError:
    print "Doesn't exist"
else
    print "Exists"

I think what you are looking for is hasattr. However, I'd recommend something like this if you want to detect python properties-

The disadvantage here is that attribute errors in the properties __get__ code are also caught.

Well, not exactly, don't use the built-in IFF you want to detect properties. Otherwise hasattr is perfectly good.

Note
Rectangle 27 0

How to know if an object has an attribute in Python?


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

@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.

@MartinGeisler Good point - it's not the same as it catches all exceptions. Not sure which version is more correct--really depends on the assumptions you're working under and who's calling your function. Thanks for clarifying.

I think the most obvious use case has nothing to do with forgiveness and is "initialise it if it's not there" for lazy initialisation. Co-location of initialisation and use in the source is often better than initialising in one place and using in another.

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

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.

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.

Note
Rectangle 27 0

How to know if an object has an attribute in Python?


try:
    doStuff(a.property)
except AttributeError:
    otherStuff()
try:
    val = a.property
except AttributeError:
    otherStuff()
else:
    doStuff(val)

The user @jpalecek mentioned it: If an AttributeError occurs inside doStuff(), you are lost.

Note
Rectangle 27 0

How to know if an object has an attribute in Python?


a = SomeClass()
try:
    return a.fake_prop
except AttributeError:
    return default_value

+1. This is even safer than using hasattr when SomeClass overrides __getattr__ since hasattr will catch all exceptions in Python 2.x, not just AttributeError like you would expect. This was fixed in Python 3.2 please see my other answer for a simple workaround.

According to pydoc, hasattr(obj, prop) simply calls getattr(obj, prop) and catches exceptions. So, it is just as valid to wrap the attribute access with a try statement and catch AttributeError as it is to use hasattr() beforehand.

Well hasattr actually may be optimized. E.g. with pypy.

Note
Rectangle 27 0

How to know if an object has an attribute in Python?


if hasattr(a, 'property'):
    doStuff(a.property)
else:
    otherStuff()
try:
    doStuff(a.property)
except AttributeError:
    otherStuff()

@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.

@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.

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:

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.

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.

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.

Note
Rectangle 27 0

How to know if an object has an attribute in Python?


Depending on the situation you can check with isinstance what kind of object you have, and then use the corresponding attributes. With the introduction of abstract base classes in Python 2.6/3.0 this approach has also become much more powerful (basically ABCs allow for a more sophisticated way of duck typing).

However, I agree that in most situations the hasattr approach (described in other answers) is the most appropriate solution.

One nice example is the distinction between iterators and iterables (see this question). The __iter__ methods in an iterator and an iterable have the same name but are semantically quite different! So hasattr is useless, but isinstance together with ABC's provides a clean solution.

One situation were this is useful would be if two different objects have an attribute with the same name, but with different meaning. Using only hasattr might then lead to strange errors.

Note