python / python/cpython

Inconsistent error messages when returning the wrong type for the type-conversion magic methods

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

还没有人认领这个 Issue。

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

描述

Bug report

Bug description:

I noticed the error messages between magic methods like __int__ and __float__ were inconsistent. This seems like slightly undesirable behavior to me. I used the following code to generate many of them.

class Foo:
    def __int__(self):
        return None
    
    def __float__(self):
        return None
    
    def __bytes__(self):
        return None
    
    def __complex__(self):
        return None
    
    def __bool__(self):
        return None
    
    def __str__(self):
        return None

try:
    int(Foo())
except Exception as e:
    print(e)

try:
    float(Foo())
except Exception as e:
    print(e)

try:
    bytes(Foo())
except Exception as e:
    print(e)

try:
    complex(Foo())
except Exception as e:
    print(e)

try:
    bool(Foo())
except Exception as e:
    print(e)

try:
    str(Foo())
except Exception as e:
    print(e)

And the output is as follows:

__int__ returned non-int (type NoneType)
Foo.__float__ returned non-float (type NoneType)
__bytes__ returned non-bytes (type NoneType)
__complex__ returned non-complex (type NoneType)
__bool__ should return bool, returned NoneType
__str__ returned non-string (type NoneType)

The first issue I've made, but seems like a reasonable bug. I'm not sure if there are other "type-conversion" magic methods out there that aren't consistent.

CPython versions tested on:

3.13, 3.12

Operating systems tested on:

Windows

Linked PRs
  • gh-130835
  • gh-144737
  • gh-144827
  • gh-151894
  • gh-154606
  • gh-156080
  • gh-156120

贡献指南

打开贡献指南

从这里开始

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

调研方向

首先运行 issue 的复现程序,并比较每个类型转换 magic 方法报告的消息。查看链接的 PR,以确定哪些情况已经得到处理、还剩下什么;完成意味着相关错误消息具有经过约定的一致行为,并有回归测试覆盖。

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

评估

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

把新 issue 发到你的邮箱

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