Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, is this a good practice?

Tags:

python

try:
    spam.foo
except AttributeError:
    do_somthing()

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

like image 818
orokusaki Avatar asked Dec 22 '25 01:12

orokusaki


1 Answers

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.

like image 125
Felix Kling Avatar answered Dec 24 '25 21:12

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!