try:
spam.foo
except AttributeError:
do_somthing()
(Is it wise to check an attribute like that without using it?)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Update:
If you are really only interested in whether the attribute
fooexists (and not doing something with the attribute) than of coursehasattr()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:The documentation of
hasattr()describes that it is implemented by: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:
So yes this is exactly the way one should do this if you more or less know that
spamwill have afooattribute most of the time (the code will be (little?) faster).Otherwise, if
spamdoes not have afooattribute (most of the time), then this approach would be better:The section on Wikipedia I linked to describes this. Quote (where the EAFP version refers to the way you wrote your code sample):
Which is somehow obvious as (with EAFP) you don’t have to introspect the object every time before you want to access the attribute.