Python's hasattr sometimes returns incorrect r

2019-04-29 03:50发布

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条回答
萌系小妹纸
2楼-- · 2019-04-29 04:08

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.

查看更多
登录 后发表回答