Skip to content

Behavior change for foo and 1 or 2: 3.12 newly converts foo to bool twice #124285

@frigus02

Description

@frigus02

Bug report

Bug description:

We noticed a behavior change between 3.11 and 3.12. The following code calls Foo.__bool__ once in 3.11 and twice in 3.12. Consequently for this contrived example, the expression evaluates to different results in 3.11 and 3.12.

class Foo:
    def __init__(self):
        self._a = True
    def __bool__(self):
        self._a = not self._a
        print(f"Foo.__bool__ -> {self._a}")
        return self._a

Foo() and "a string" or 42

In Python 3.11:

>>> Foo() and "a string" or 42
Foo.__bool__ -> False
42

In Python 3.12 (and 3.13.0b2):

>>> Foo() and "a string" or 42
Foo.__bool__ -> False
Foo.__bool__ -> True
<__main__.Foo object at 0x7f0ae554c1a0>

Is this change intentional?

Note that I'm not necessarily asking to change this. We should arguably change the code to "a string" if Foo() else 42, which evaluates the same in 3.11 and 3.12.

CPython versions tested on:

3.12

Operating systems tested on:

Linux

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.14new features, bugs and security fixesinterpreter-core(Objects, Python, Grammar, and Parser dirs)type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions