`get_original_bases` does not return what `cls.__orig_bases__` returns
未關閉
還沒有人認領這個 Issue。
docs
topic-typing
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 36k
- PR 合併指標
- PR 指標待擷取
描述
Bug report
Bug description:
The types documentation states for the types.get_original_bases function:
For classes that have an
__orig_bases__attribute, this function returns the value ofcls.__orig_bases__. For classes without the__orig_bases__attribute,cls.__bases__is returned.
I need the functionality of cls.__orig_bases__, but need to use types.get_original_bases to make the type checker happy.
A short MRE:
from types import get_original_bases
from typing import Generic, TypeVar
T = TypeVar("T")
class One(Generic[T]):
pass
class Two(One[int]):
pass
class Three(Two):
pass
assert get_original_bases(One) == One.__orig_bases__
assert get_original_bases(Two) == Two.__orig_bases__
assert get_original_bases(Three) == Three.__orig_bases__
# Traceback (most recent call last):
# File "c:\<cut>\test.py", line 34, in <module>
# assert get_original_bases(Three) == Three.__orig_bases__
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# AssertionError
This is a easy solve, I would be happy to add a PR. Change here:
try:
- return cls.__dict__.get("__orig_bases__", cls.__bases__)
+ return getattr(cls, "__orig_bases__", cls.__bases__)
except AttributeError:
raise TypeError(
f"Expected an instance of type, not {type(cls).__name__!r}"
) from None
To show this works:
from typing import Generic, TypeVar
T = TypeVar("T")
class One(Generic[T]):
pass
class Two(One[int]):
pass
class Three(Two):
pass
def better_get_original_bases(cls):
try:
return getattr(cls, "__orig_bases__", cls.__bases__)
except AttributeError:
raise TypeError(
f"Expected an instance of type, not {type(cls).__name__!r}"
) from None
assert better_get_original_bases(One) == One.__orig_bases__
assert better_get_original_bases(Two) == Two.__orig_bases__
assert better_get_original_bases(Three) == Three.__orig_bases__
# <No output>
CPython versions tested on:
3.12
Operating systems tested on:
Windows
Linked PRs
- gh-156917
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
從 Lib/types.py 中的 get_original_bases 開始,重現 issue 中的繼承範例,包括 Three 類別的情況。函式符合文件所述的 original-bases 行為,且回歸測試涵蓋範圍驗證了繼承屬性的情況,即視為完成;開始前請查看相關的 PR gh-156917。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- python
- 領域
- tooling
- Issue 類型
- 缺陷
- 難度
- 2/5
- 預估耗時
- 1-3 小時
- 活躍度
- 停滯
- 描述清晰度
- 描述清楚
- 新手友好度
- 25/100