[Tutor] atr in dir Vs. hasattr

Tim Johnson tim at johnsons-web.com
Wed Mar 16 02:54:37 CET 2011


* Wayne Werner <waynejwerner at gmail.com> [110315 17:29]:
> On Tue, Mar 15, 2011 at 8:00 PM, Tim Johnson <tim at johnsons-web.com> wrote:
> 
> >  What is the difference between using
> >  hasattr(object, name)
> >  and
> >  name in dir(object)
> >
> 
> hasattr is basically
> 
> try:
>     object.name
>     return True
> except AttributeError:
>     return False
> 
> while "name in dir(object)" is (AFAIK) more like:
> 
> for attr in dir(object):
>     if name == attr: return True
> return False
 
   Wayne, that is interesting to read. I'm glad I read it.

> 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, 2) in
> Python it's EAFP - Easier to Ask Forgivness than Permission, 3) You
> shouldn't inspect an object to find out what it can do, you should just try
> it and then handle failures appropriately (at least that's what I've been
> told).
> 
> HTH,
  Yes it helps, including the distinction between the two try/except
  blocks.

  On another note, I made an error in the original posting. I
  did a 'reply' rather than a direct 'send' thus this thread
  is under the topic heading of a different thread. I will repost
  with your reply.

  thanks.
-- 
Tim 
tim at johnsons-web dot com or akwebsoft dot com
http://www.akwebsoft.com


More information about the Tutor mailing list