开发者

In Python, is this a good practice?

t开发者_如何学Pythonry:
    spam.foo
except AttributeError:
    do_somthing()

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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜