Repository navigation
Description
Bug report
Bug description:
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.
class HiddenDescriptor:
def __get__(self, obj, typ=None):
raise AttributeError("Hidden")
class OnlyLen:
def __len__(self):
return -1
class WithBool:
__bool__ = HiddenDescriptor()
def __len__(self):
return -1
try:
print("bool(OnlyLen()) is", bool(OnlyLen()))
except Exception as e:
print(f"bool(OnlyLen()) raises {type(e).__name__}: {e}")
try:
print("bool(WithBool()) is", bool(WithBool()))
except Exception as e:
print(f"bool(WithBool()) raises {type(e).__name__}: {e}")Output:
Python 3.13.18:
bool(OnlyLen()) raises ValueError: __len__() should return >= 0
bool(WithBool()) raises AttributeError: Hidden
Python 3.14.10:
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.
cc @corona10
CPython versions tested on:
3.14, CPython main branch
Operating systems tested on:
Linux
Activity
tonghuaroot commentedon Nov 27, 2026
i tried making the length method return an int subclass with value zero whose truth test returns true. len returns zero in both cases. bool returns false without the descriptor and true with it.
corona10 commentedon Nov 29, 2026
@etyu39
I think that the change should be something like this:
It checks
__bool__is not existed than check__len__logic as intended.You will need to add unittest when you submit the PR.
@JelleZijlstra, would you like to give some feedback to @etyu39 ?
Then the output will be something like this:
cc @colesbury (Related to original regression)
etyu39 commentedon Nov 30, 2026
Thanks for the additional example and the suggested fix! I've opened PR based on the suggestion.