Python's hasattr sometimes returns incorrect results

半城伤御伤魂 提交于 2019-12-07 01:47:23

问题


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 calling getattr(object, name) and seeing whether it raises an AttributeError 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!