Why does hasattr
say that the instance doesn't have a foo
attribute?
>>> class A(object):
... @property
... def foo(self):
... ErrorErrorError
...
>>> a = A()
>>> hasattr(a, 'foo')
False
I expected:
>>> hasattr(a, 'foo')
NameError: name 'ErrorErrorError' is not defined`
The Python 2 implementation of
hasattr
is fairly naive, it just tries to access that attribute and see whether it raises an exception or not.Unfortunately,
hasattr
will eat any exception type, not just anAttributeError
matching the name of the attribute which was attempted to access. It caught aNameError
in the example shown, which causes the incorrect result ofFalse
to be returned there. To add insult to injury, any unhandled exceptions inside properties will get swallowed, and errors inside property code can get lost, masking bugs.In Python 3.2+, the behavior has been corrected:
The fix is here, but that change didn't get backported.
If the Python 2 behavior causes trouble for you, consider to avoid using
hasattr
; instead you can use a try/except aroundgetattr
, catching only theAttributeError
exception type and letting any other exceptions raise unhandled.