问题
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`
回答1:
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 returned True
if anything).
In python3.2+, the behaviour has been corrected:
hasattr(object, name)
The arguments are an object and a string. The result is
True
if the string is the name of one of the object’s attributes,False
if not. (This is implemented by callinggetattr(object, name)
and seeing whether it raises anAttributeError
or not.)
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 around getattr, catching only the AttributeError
exception and letting any others raise unhandled.
来源:https://stackoverflow.com/questions/35566680/pythons-hasattr-sometimes-returns-incorrect-results