[Python-Dev] 'hasattr' is broken by design
P.J. Eby
pje at telecommunity.com
Tue Aug 24 00:39:03 CEST 2010
At 12:02 AM 8/24/2010 +0300, Michael Foord wrote:
>For properties there is *no reason* why code should be executed
>merely in order to discover if the attribute exists or not.
That depends on what you mean by "exists". Note that a property
might raise AttributeError to signal that the attribute is not
currently set. Likewise, unless you special case __slots__
descriptors, you can have the bizarre condition where hasattr() will
return True, but getattr() will still raise an AttributeError.
The idea that you could determine the presence of an attribute on an
object without executing that object's code is something that hasn't
been practical since the birth of descriptors in Python 2.2.
>Yes I know the dance (walking the mro fetching the attribute out of
>the appropriate type __dict__ or the instance dict - or looking on
>the metaclass if the object you are introspecting is a type itself),
>it is just not trivial - which is why I think it is a shame that
>people are forced to implement it just to ask if a member exists
>without triggering code execution.
Even if you implement it, you will get wrong answers in some
cases. __getattribute__ is allowed to throw out the entire algorithm
you just described and replace it utterly with something else.
My ProxyTypes library makes use of that fact, for example, so if you
actually attempted to inspect a proxy instance with your
re-implemented "dance", your code will fail to notice what attributes
the proxy actually has.
More information about the Python-Dev
mailing list