[Tutor] atr in dir Vs. hasattr

Steven D'Aprano steve at pearwood.info
Wed Mar 16 14:19:34 CET 2011

Wayne Werner wrote:

> However, rare is the occasion that you should use either of these. If you're
> doing something like:
> if hasattr(myobj, 'something'):
>    myobj.something()
> else:
>     print "blah blah blah"
> then what you really should be doing is:
> try:
>     myobj.something()
> except AttributeError:
>     print "blah blah blah"
> because 1) you avoid the overhead of an extra(?) try-except block, 

But there is no extra try-except block, because you've just explained 
that hasattr itself contains a try-except block. The only difference is 
whether it is explicit in your own code, or implicit inside hasattr.

More likely though, hasattr (like its cousins getattr and setattr) will 
be used when the attribute name isn't known until runtime, rather than 
for fixed strings:

name = get_some_name_from_somewhere(arg)
if hasattr(myobj, name):
     result = getattr(myobj, name)

Of course, you could do this instead:

     result = getattr(myobj, name)
except AttributeError:

or even this:

result = getattr(myobj, name, default_value)


More information about the Tutor mailing list