python / python/cpython

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

未关闭
#124,285 18 条评论 5 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

3.14 docs interpreter-core type-bug
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

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
  • gh-124394
  • gh-124723

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

在 Python 3.11、3.12 和 3.13 上运行提供的 Foo.__bool__ reproducer,然后查看相关联的 PR gh-124394 和 gh-124723,了解当前方向。完成的标准是:行为变化已得到解决或被明确记录,有回归测试覆盖,并且预期结果清晰明确。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
compilers
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
需要澄清
新手友好度
20/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。