Improve error message for return in metaclass __new__()
還沒有人認領這個 Issue。
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 36k
- 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:
- Metaclass usage is already an advanced topic.
- Improving the DX (developer experience) here will help advanced learners and reduce friction.
- 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
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
先重現 issue 中描述的兩個 metaclass new 情況,並追蹤引發目前 TypeError 的執行階段進入點。更新缺少回傳值或回傳值不是類別時的診斷資訊,接著為兩個範例加入涵蓋範圍,並確認訊息清楚說明所需的回傳值。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- python
- 領域
- compilers
- Issue 類型
- 功能
- 難度
- 3/5
- 預估耗時
- 1-2 天
- 活躍度
- 停滯
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100