[Python-Dev] 'hasattr' is broken by design

Michael Foord fuzzyman at voidspace.org.uk
Mon Aug 23 23:02:42 CEST 2010


  On 23/08/2010 23:55, Benjamin Peterson wrote:
> 2010/8/23 Raymond Hettinger<raymond.hettinger at gmail.com>:
>> On Aug 23, 2010, at 1:13 PM, Benjamin Peterson wrote:
>>
>>> 2010/8/23 Michael Foord<fuzzyman at voidspace.org.uk>:
>>>> To me hasattr *looks* like a passive introspection function, and the fact
>>>> that it can trigger arbitrary code execution is unfortunate - especially
>>>> because a full workaround is pretty arcane.
> hasattr(x, "y") doesn't look any more passive to me the x.y.
One says "does this object have attribute y" the other fetches attribute 
y. I'm amazed they don't look different to you. Given Python's object 
model there is no reason that the first *should* fetch the attribute to 
determine that it is present, *except* for the dynamic attribute 
creation of __getattr__ and __getattribute__.

For properties there is *no reason* why code should be executed merely 
in order to discover if the attribute exists or not.

I'm in both camps though. As we *are* triggering code execution I don't 
think we should mask exceptions. I just wish we weren't triggering code 
execution unnecessarily.

Michael


>> Well said.  The surprise to me in the OP's example was that
>> the property() was executed.  Regular methods aren't run
>> by hasattr() so it's hard to remember that when writing code using hasattr().
> Hard to remember compared to what?
>
>> That is especially unfortunate because someone turning a regular
>> attribute into a property may be doing so long after client code has
>> been written (IIRC, that was a key use case for properties).
>> IOW, the user of the hasattr() may have had no way
>> of knowing that an exception could ever be raised
>> (because it is perfectly safe with regular attributes and methods).
> Better to raise an exception into unexpecting code that to have subtly
> different lookup rules between getattr and hasattr.
>
>


-- 
http://www.ironpythoninaction.com/



More information about the Python-Dev mailing list