python / python/cpython

Improve metaclass conflict error message with clearer terminology and contextual information

未關閉
#134,902 2 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

interpreter-core type-feature
主要語言
Python
星號
77.2k
分支
35.9k
PR 合併指標
PR 指標待擷取

描述

Feature or enhancement

Proposal:

Improve Metaclass Conflict Error Message

Summary

Improve the error message raised during metaclass conflicts to specify the
base with incompatible metaclass.


Motivation

Class inheritance has a well-established terminology across languages, but
Python's metaclass system introduces a distinct mechanism that lacks clear
linguistic conventions. This feature proposes the following
terminologies.

  • A class is derived from its metaclass
  • A class is based on its base classes
  • A metaclass is any subclass of type

Example

In the following code, MetaFoo and MetaBar are both subclasses of type
making them metaclasses according to the previous terminology suggestion.
Since neither is a subclass of the other, they are incompatible as metaclasses.
Foo derives from MetaFoo and Bar derives from MetaBar, but because
Bar is based on Foo; the conflicting metaclasses cause the TypeError
relating to metaclass conflict.

class MetaFoo(type): pass

class MetaBar(type): pass

class Foo(metaclass=MetaFoo): pass

class Bar(Foo, metaclass=MetaBar): pass  # raises

Current Behaviour

The TypeError currently raised looks like this:

TypeError: metaclass conflict: the metaclass of a derived class must be a
(non-strict) subclass of the metaclasses of all its bases

Proposed Behaviour

The improved error message would add contextual details and adopt the new
terminology: (Line breaks included for clarity).

Metaclass conflict while creating a new class!
- Declared metaclass: 'MetaBar'
- Incompatible base class: 'Foo'
- That base is derived from metaclass: 'MetaFoo'
All base classes must be based on classes derived from the same metaclass or a
subclass thereof.

Notes

This change requires changes to the _PyType_CalculateMetaclass function only.
Including the name (Bar in the example) in the error message would require
changes to multiple functions across the codebase.

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 中提到的 _PyType_CalculateMetaclass 函式開始,並重現 MetaFoo、MetaBar、Foo 和 Bar 範例。將產生的 TypeError 與提議的措辭進行比較,其中應包括宣告的元類別、不相容的基底類別及其元類別;完成的標準是,該衝突使用所述術語回報這些上下文資訊。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
python
領域
backend
Issue 類型
功能
難度
3/5
預估耗時
1-2 天
活躍度
停滯
描述清晰度
描述清楚
新手友好度
45/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。