python / python/cpython

Improve error message for return in metaclass __new__()

未关闭
#132,343 2 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

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

描述

Feature or enhancement

Proposal:

Case1: When overriding new in a custom Meta class and forgetting to return a class object (e.g. by omitting return super().new(..)) Python raises the following error:
TypeError: 'NoneType' object is not callable

Case2: When returning something else other than class object it raises following error:
TypeError: 'str' object is not callable

This messages, while technically correct, lacks guidance for common scenarios and can confuse developers - especially those new to Meta class.

Steps to Reproduce:

Case1:
class NewMeta(type):
def new(cls, name, bases, dct):
print ("Forgot to return!")

class MyClass(metaclass = NewMeta):
def greet(self):
pass

m = MyClass()

Output: TypeError: 'NoneType' object is not callable

Case2:
class NewMeta(type):
def new(cls, name, bases, dct):
return ("Return non-callable object")

class MyClass(metaclass = NewMeta):
def greet(self):
pass

m = MyClass()

Output: TypeError: 'str' object is not callable

Suggested Improvement:
Improve the error message to something like:
TypeError: metaclass new must return a class object. Recommendation: super().new(metacls, name, bases, namespace)?

This small change could save significant debugging time and make advanced features like metaclasses more approachable.

Python Version:
Tested in Python 3.12.4 (tags/v3.12.4:8e8a4ba, Jun 6 2024, 19:30:16) [MSC v.1940 64 bit (AMD64)]

Why This Matters:

  1. Metaclass usage is already an advanced topic.
  2. Improving the DX (developer experience) here will help advanced learners and reduce friction.
  3. Similar improvements have already been adopted in recent Python versions for other common errors.
Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

贡献指南

打开贡献指南

从这里开始

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

调研方向

首先重现 issue 中描述的两个 metaclass new 情况,并跟踪引发当前 TypeError 的运行时入口点。更新缺少返回值或返回值不是类时的诊断信息,然后为两个示例添加覆盖,并验证这些消息能够清楚地解释所需的返回值。

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

评估

技术栈
python
领域
compilers
Issue 类型
功能
难度
3/5
预计耗时
1-2 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 发到你的邮箱

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