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

Michael Foord fuzzyman at voidspace.org.uk
Mon Aug 23 23:09:06 CEST 2010


  On 24/08/2010 00:05, Benjamin Peterson wrote:
> 2010/8/23 Michael Foord<fuzzyman at voidspace.org.uk>:
>>   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__.
> Actually, I'd say given Python's object model, you have to have the
> attribute in hand to determine that it is present.
>
>> For properties there is *no reason* why code should be executed merely in
>> order to discover if the attribute exists or not.
> Properties are allowed to raise AttributeError, so you technically
> have to execute it.
>
Properties are allowed to do whatever the heck they want. That doesn't 
mean that you have to execute code to determine whether they exist or not.

If fetching an attribute raises an AttributeError it doesn't mean that 
attribute doesn't exist (although I admit that at the moment this is 
exactly what hasattr uses to mean) it just means that fetching that 
attribute raised an AttributeError. Even if you allow other exceptions 
to propagate you are still left with the fact that an AttributeError 
raised as a bug will still be silenced and interpreted as meaning that 
hasattr should just return False.

Michael Foord

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



More information about the Python-Dev mailing list