On Tue, Mar 15, 2011 at 8:00 PM, Tim Johnson <[email protected]> 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
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
> ?
> TIA
> --
> Tim
> tim at johnsons-web dot com or akwebsoft dot com
> http://www.akwebsoft.com
> _______________________________________________
> Tutor maillist - [email protected]
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor