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

Linked PRs

Activity

  1. added
    type-bug
    on Nov 26, 2026
  2. added
    interpreter-core
    on Nov 26, 2026
  3. tonghuaroot commented on Nov 27, 2026

    @tonghuaroot
    Contributor

    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.

  4. corona10 commented on Nov 29, 2026

    @corona10
    Member

    @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.

    diff --git a/Objects/typeobject.c b/Objects/typeobject.c
    index a2690e8e6aa..9beb112edac 100644
    --- a/Objects/typeobject.c
    +++ b/Objects/typeobject.c
    @@ -10709,15 +10709,10 @@ FUNCNAME(PyObject *self, PyObject *other) \
         SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, DUNDER, RDUNDER)
    
     static Py_ssize_t
    -slot_sq_length(PyObject *self)
    +len_result_as_ssize_t(PyObject *res)
     {
    -    PyObject* stack[1] = {self};
    -    PyObject *res = vectorcall_method(&_Py_ID(__len__), stack, 1);
         Py_ssize_t len;
    
    -    if (res == NULL)
    -        return -1;
    -
         Py_SETREF(res, _PyNumber_Index(res));
         if (res == NULL)
             return -1;
    @@ -10736,6 +10731,17 @@ slot_sq_length(PyObject *self)
         return len;
     }
    
    +static Py_ssize_t
    +slot_sq_length(PyObject *self)
    +{
    +    PyObject* stack[1] = {self};
    +    PyObject *res = vectorcall_method(&_Py_ID(__len__), stack, 1);
    +    if (res == NULL) {
    +        return -1;
    +    }
    +    return len_result_as_ssize_t(res);
    +}
    +
     static PyObject *
     slot_sq_item(PyObject *self, Py_ssize_t i)
     {
    @@ -10895,7 +10901,6 @@ SLOT0(slot_nb_absolute, __abs__)
     static int
     slot_nb_bool(PyObject *self)
     {
    -    int using_len = 0;
         int attr_is_none = 0;
         PyObject *value = maybe_call_special_no_args(self, &_Py_ID(__bool__),
                                                      &attr_is_none);
    @@ -10907,10 +10912,11 @@ slot_nb_bool(PyObject *self)
         }
         else if (value == NULL && !PyErr_Occurred()) {
             value = _PyObject_MaybeCallSpecialNoArgs(self, &_Py_ID(__len__));
    -        if (value == NULL && !PyErr_Occurred()) {
    -            return 1;
    +        if (value == NULL) {
    +            return PyErr_Occurred() ? -1 : 1;
             }
    -        using_len = 1;
    +        Py_ssize_t len = len_result_as_ssize_t(value);
    +        return len < 0 ? -1 : len > 0;
         }
    
         if (value == NULL) {
    @@ -10918,11 +10924,7 @@ slot_nb_bool(PyObject *self)
         }
    
         int result;
    -    if (using_len) {
    -        /* bool type enforced by slot_nb_len */
    -        result = PyObject_IsTrue(value);
    -    }
    -    else if (PyBool_Check(value)) {
    +    if (PyBool_Check(value)) {
             result = PyObject_IsTrue(value);
         }
         else {

    @JelleZijlstra, would you like to give some feedback to @etyu39 ?

    Then the output will be something like this:

    bool(OnlyLen()) raises ValueError: __len__() should return >= 0
    bool(WithBool()) raises ValueError: __len__() should return >= 0
    

    cc @colesbury (Related to original regression)

  5. added
    needs backport to 3.14
    needs backport to 3.15
    on Nov 30, 2026
  6. etyu39 commented on Nov 30, 2026

    @etyu39
    Author

    Thanks for the additional example and the suggested fix! I've opened PR based on the suggestion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

interpreter-coreneeds backport to 3.14needs backport to 3.15type-bug

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions