Python's hasattr sometimes returns incorrect results

荒凉一梦 提交于 2019-12-05 08:19:23

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.

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