[Tutor] atr in dir Vs. hasattr

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


This following post was originally posted to the wrong thread.
I am reposting (hopefully correctly) with the first and very
succint response. I thing the answer is a revealation to
be noted: 
##########################################################
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)

##########################################################
Wayne Werner <waynejwerner at gmail.com> Replied:
##########################################################
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

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

YMMV, objects in mirror are closer than they appear, etc. etc.

HTH,
Wayne

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


More information about the Tutor mailing list