Python's hasattr sometimes returns incorrect results
Asked Answered
C

1

6

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`
Cholecalciferol answered 23/2, 2016 at 0:37 Comment(0)
C
15

The Python 2 implementation of hasattr is fairly naive, it just tries to access that attribute and see whether it raises an exception or not.

Unfortunately, hasattr will eat any exception type, not just an AttributeError matching the name of the attribute which was attempted to access. It caught a NameError in the example shown, which causes the incorrect result of False to be returned there. To add insult to injury, any unhandled exceptions inside properties will get swallowed, and errors inside property code can get lost, masking bugs.

In Python 3.2+, the behavior 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 that change didn't get backported.

If the Python 2 behavior causes trouble for you, consider to avoid using hasattr; instead you can use a try/except around getattr, catching only the AttributeError exception type and letting any other exceptions raise unhandled.

Cholecalciferol answered 23/2, 2016 at 0:37 Comment(2)
The quote from the Python docs notwithstanding, hasattr behaviour may still be considered strange. It's true that arbitrary exceptions inside a property no longer cause the attribute to be considered absent (but rather get raised right in the caller's face), but if an AttributeError originates from somewhere within the property, the result of hasattr will still be False. This may not be intentional. (Or it may, so a property can determine itself whether it wants to be "there".) In any case, executing the property sounds wrong to me in the first place, considering side effects etc.Anguine
There is not really a straightforward way to determine whether an AttributeError was raised by the attribute-getting machinery itself, or by code in a property.Groan

© 2022 - 2024 — McMap. All rights reserved.