`get_original_bases` does not return what `cls.__orig_bases__` returns
未关闭
还没有人认领这个 Issue。
docs
topic-typing
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 35.9k
- 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