'if foo' calls getattr?!?

Robin Becker robin at jessikat.demon.co.uk
Mon Aug 30 14:16:47 EDT 1999


In article <joe-300819991050234291 at chinacat.salk.edu>, Joe Strout
<joe at strout.net> writes
>[[ This message was both posted and mailed: see
>   the "To," "Cc," and "Newsgroups" headers for details. ]]
>
>Doing some profiling on Graphite this weekend, we found a very curious
>thing: a gazillion calls to __getattr__ on one of our classes, where we
>expected to find none.  We eventually tracked it down to a seemingly
>innocent test, basically, "if foo: self.myfoo = foo".  The "if foo" was
>invoking foo.__getattr__ (which is very expensive).
>
>I can think of no reason why it should be this way, but it is.  Below is
>a very simple stand-alone demonstration.  It leads me to the absurd
>idiom of saying "if id(foo) != id(None)" when I really mean "if foo",
>just because using id() avoids the __getattr__ call.
>
>Can anybody explain why this should be?  Is it a bug in Python?  Is
>there some other way to check whether I have a reference to an object
>that doesn't involve a function call?
>
>Confused,
...
It seems that it tries to call foo.__nonzero__()  and then foo.__len__()
to test whether foo is true in some sense.

I think these are standard behaviours for class instances. I think you
should consider using if not foo is None: pass
-- 
Robin Becker




More information about the Python-list mailing list