[Python-Dev] hasattr and properties

Thomas Lotze tl at gocept.com
Wed Dec 7 19:40:36 CET 2005


I've noticed some behaviour of hasattr when used on properties which I'm
inclined to call a bug, or at least unexpected behaviour:

Python 2.4.2 (#1, Oct 29 2005, 13:11:33) 
[GCC 3.3.6 (Gentoo 3.3.6, ssp-3.3.6-1.0, pie-8.7.8)] on linux2
>>> class Foo(object):
...     def get(self):
...         print "hi there"
...         raise Exception
...     bar = property(get)
>>> hasattr(Foo, "bar")
>>> hasattr(Foo(), "bar")
hi there

One would expect hasattr to yield the same result in both cases, and the
result to be True.

Apparently, when applied to a class instance, hasattr calls getattr and
decides that the attribute doesn't exist if the call raises any exception.

- Wouldn't it make sense to only report a missing attribute if an
AttributeError is raised?

- As far as properties are concerned, it would make even more sense to not
call getattr but try to look up the attribute the same way getattr would.
This would, however, not work consistently anymore if one customizes
attribute access. Has anyone thought about that matter?


More information about the Python-Dev mailing list