'if foo' calls getattr?!?
David Ascher
da at ski.org
Mon Aug 30 14:05:59 EDT 1999
On Mon, 30 Aug 1999, Joe Strout wrote:
> [[ 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?
Use 'if foo is not None' to do identity checking and not truth testing.
You're getting a getattr call because your class might define its own way
of testing truth -- for more details, see:
http://www.python.org/doc/current/ref/customization.html#l2h-134
--david
More information about the Python-list
mailing list