[Tutor] atr in dir Vs. hasattr
Wayne Werner
waynejwerner at gmail.com
Wed Mar 16 02:24:27 CET 2011
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
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 - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110315/71871f0f/attachment.html>
More information about the Tutor
mailing list