hasattr + __getattr__: I think this is Python bug

Duncan Booth duncan.booth at invalid.invalid
Tue Jul 20 07:14:55 EDT 2010


dmitrey <dmitrey.kroshko at scipy.org> wrote:

> hi all,
> I have a class (FuncDesigner oofun) that has no attribute "size", but
> it is overloaded in __getattr__, so if someone invokes
> "myObject.size", it is generated (as another oofun) and connected to
> myObject as attribute.
> 
> So, when I invoke in other code part "hasattr(myObject, 'size')",
> instead o returning True/False it goes to __getattr__ and starts
> constructor for another one oofun, that wasn't intended behaviour.
> Thus "hasattr(myObject, 'size')" always returns True. It prevents me
> of some bonuses and new features to be done in FuncDesigner.
> 
>>>> 'size' in dir(b)
> False
>>>> hasattr(b,'size')
> True
>>>> 'size' in dir(b)
> True
> 
> Could you fix it?

This isn't a bug, it is by design: try reading the documentation for 
'hasattr' as that explains that it is implemented by calling getattr and 
seeing whether or not it throws an exception.

If you want different behaviour you just need to define your own helper 
function that has the behaviour you desire. e.g. one that just looks in the 
object's dictionary so as to avoid returning true for properties or other 
such fancy attributes.

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list