tags:

views:

153

answers:

2
try:
    spam.foo
except AttributeError:
    do_somthing()

(Is it wise to check an attribute like that without using it?)

+10  A: 

Update:

If you are really only interested in whether the attribute foo exists (and not doing something with the attribute) than of course hasattr() might be better way to check for the attribute.
From a developer/user point of view I have to confess that, for me, the use of hasattr() better reflects your intention. And besides that it would result in less code:

if not hasattr(spam,'foo'):
    do_something()

The documentation of hasattr() describes that it is implemented by:

(This is implemented by) calling getattr(object, name) and seeing whether it raises an exception or not.

So basically hasattr() does exactly the same as you are doing. In this case I would definitely go with the build in solution, i.e. hasattr(). You won't gain any speed advantage.


Python encourages the EAFP paradigm:

It is Easier to Ask for Forgiveness than Permission

So yes this is exactly the way one should do this if you more or less know that spam will have a foo attribute most of the time (the code will be (little?) faster).
Otherwise, if spam does not have a foo attribute (most of the time), then this approach would be better:

if hasattr(spam, 'foo'):
    bar = spam.foo
else:
    do_somthing()

The section on Wikipedia I linked to describes this. Quote (where the EAFP version refers to the way you wrote your code sample):

These two code samples have the same effect, although there will be performance differences. When spam has the attribute eggs, the EAFP sample will run faster. When spam does not have the attribute eggs (the "exceptional" case), the EAFP sample will run slower. (...) If exceptional cases are rare, then the EAFP version will have superior average performance than the alternative.

Which is somehow obvious as (with EAFP) you don't have to introspect the object every time before you want to access the attribute.

Felix Kling
@felix Is this still the case in my case (where I'm not using the attribute at all in the "try" context)? Is it still considered Pythonic?
orokusaki
I think `try...catch` is bad idea. Avoid them if you can even if `It is Easier to Ask for Forgiveness than Permission` .
TheMachineCharmer
@orokusaki: why would you need to do it if you're not using the attribute? If you're testing to work out what type of object it is, then no, that's not considered Pythonic. Instead it's typical to use the object in the way you were hoping to use it and handle any exception that results. Better still, examine why you have a function that takes a variety of objects with disparate interfaces.
Kylotan
It's a higher order function that checks the attribute for existence and alters the function if it's not set.
orokusaki
+2  A: 

Better use

if hasattr(spam,"foo"):
   #dosomthing with spam.foo
else:
   do_somthing()

Python docs:

hasattr(object, name)
The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an exception or not.)

TheMachineCharmer
If you want to check for `spam.foo`, you would use `hasattr(spam, "foo")`. `hasattr(spam, foo)` assumes that `foo` is a variable holding a string, and checks `spam` for the attribute named by the string.
Chris Lutz
Ooops!! See it corrected.Thanks Chris.
TheMachineCharmer
+1 for your answer. I chose Felix' answer because if a visitor finds this question, I think it's important for them to understand both angles. With his answer it's now less of a "which to use?" and more of a "use the interface for style, or use the implementation for speed?".
orokusaki
@orokusaki: I updated my answer again. Your code is exactly the way `hasattr` is implemented (I noticed this now). So I would go with `hasattr` as you probably don't get a measurable speed advantage.
Felix Kling
@orokusaki That is exactly what I thought :) and have already given felix +1 for considering both the angles. ;)
TheMachineCharmer