You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
__len__ result is not validated in truth testing when a __bool__ descriptor raises AttributeError #162678
Since 3.14, if the __get__ method of a __bool__ descriptor raises AttributeError during truth value testing, the object is treated as if it had no __bool__, and evaluation falls back to __len__. On this fallback path, the result of __len__ is not validated. As a result, even if __len__ returns something other than a non-negative integer, such as -1 or "abc", no exception is raised.
bool(OnlyLen()) raises ValueError: __len__() should return >= 0
bool(WithBool()) is True
I found this behavior while writing a mechanized specification of Python bytecode semantics, specifically while specifying truth value testing.
Suspected cause
This behavior appears to have been introduced by GH-131588 (gh-131586). Since that change, slot_nb_bool in Objects/typeobject.c calls __bool__ through maybe_call_special_no_args, which suppresses AttributeError. This makes the __len__ fallback path in slot_nb_bool reachable, and that path does not validate the return value of __len__. The check was already missing from this path in 3.13 and earlier, but the path could not be reached before.
I'm not sure whether it's intentional that an AttributeError from __get__ is treated as a missing method. Either way, the missing validation of the __len__ return value looks like a bug, so I think this path should apply the same checks as when only __len__ is defined.
Activity