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 python2 implementation of hasattr is fairly naive, it just tries to access that attribute and see whether it raises an exception or not.
Unfortunately, this means that any unhandled exceptions inside properties will get swallowed, and errors in that code can get lost. To add insult to injury, when hasattr eats the exception, it will also return an incorrect answer (here the attribute
a.foo
does exist, so the result should have returnedTrue
if anything).In python3.2+, the behaviour has been corrected:
The fix is here, but unfortunately that change didn't backport.
If the python2 behaviour causes trouble for you, consider to avoid using
hasattr
; instead you can use a try/except aroundgetattr
, catching only theAttributeError
exception and letting any others raise unhandled.