Skip to content

__len__ result is not validated in truth testing when a __bool__ descriptor raises AttributeError #162678

Todo

Description

@etyu39

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

  1. added
    type-bug
    on Nov 26, 2026
  2. added
    interpreter-core
    on Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

interpreter-coretype-bug

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions