the python2 hasattr implementation is pretty naive, it just tries to access this attribute and see if this throws an exception or not.
Unfortunately, this means that any unhandled exceptions inside the properties will be swallowed, and errors in this code may be lost. To add insult to injury, when hasattrt is the exception, it will also return an incorrect answer (here the a.foo attribute exists, so the result should have returned True if something).
In python3.2 +, the behavior is fixed:
hasattr(object, name)
Arguments are an object and a string. The result is True if the string is the name of one of the attributes of the objects, False if not. (This is implemented by calling getattr(object, name) and looking to see if it raises AttributeError or not.)
The fix is here , but unfortunately this change was not the other way around.
If python2's behavior is causing you problems, consider not using hasattr ; instead, you can use try / except getattr , catching only the AttributeError exception and letting other people raise the raw ones.
source share