How to alias `Annotated` to a subscriptable type
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 1.8k
- 派生
- 302
- 平均合并
- 23 小时
- 30 天内合并 PR
- 8
描述
Hi, I want to create a type alias that simply wraps a tuple into Annotated.
I want to be able to write
SpecialReturn[int, bool, str]
And get
Annotated[Tuple[int, bool, str], 'special return!']
Among other things, I've tried:
class SpecialReturn():
def __class_getitem__(self, params: Tuple[Any, ...]) -> Tuple[Any, ...]:
return typing.cast(
Tuple[Any, ...],
_typing.Annotated[
typing.Tuple.__getitem__(params),
'multiple_return',
]
)
Which mypy is happy with the declaration, but not using it:
import typing
from typing import Annotated, Any, Tuple
class SpecialReturn():
def __class_getitem__(self, params: Tuple[Any, ...]) -> Tuple[Any, ...]:
return typing.cast(
Tuple[Any, ...],
Annotated[
typing.Tuple.__getitem__(params),
'multiple_return',
]
)
def test() -> SpecialReturn[int, int]:
return 1, 2
test8.py:17: error: "SpecialReturn" expects no type arguments, but 2 given
test8.py:18: error: Incompatible return value type (got "Tuple[int, int]", expected "SpecialReturn")
Which happens because I guess mypy does not evaluate the type annotation, it just treats SpecialReturn as a separate type. I am not sure what is the reasoning behind this, but I assume there it makes sense in some way(?).
So, is there any alternative? How do achieve this? I essentially want to alias Tuple and be able to find out at runtime if the type is a normal tuple or my special one.
My first jab at this, and what I think makes most sense to a Python developer is the following
from typing import Tuple
class SpecialReturn(Tuple):
pass
def test() -> SpecialReturn[int, int]:
return 1, 2
But mypy can't handle it either:
test.py:4: error: Missing type parameters for generic type "Tuple"
test.py:8: error: "SpecialReturn" expects no type arguments, but 2 given
test.py:9: error: Incompatible return value type (got "Tuple[int, int]", expected "SpecialReturn")
I was thinking maybe something like this was possible with Annotated, but it seems not.
贡献指南
这个仓库没有索引到贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
先阅读 PEP 593 和此 issue 中的示例,然后查看 typing project 如何表示 Annotated、泛型别名和 class_getitem。该 issue 没有指定文件、测试或实现入口,要完成它,需要确定是否应支持此行为,以及应如何对其进行规范化说明。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- devtools
- Issue 类型
- 功能
- 难度
- 5/5
- 预计耗时
- 一周以上
- 活跃度
- 停滞
- 描述清晰度
- 需要澄清
- 新手友好度
- 20/100