How to alias `Annotated` to a subscriptable type
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 1.8k
- フォーク
- 302
- 平均マージ
- 23時間
- マージ済み PR(30日)
- 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 にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず PEP 593 とこの issue の例を読み、次に typing project が Annotated、ジェネリックエイリアス、class_getitem をどのように表現しているかを確認してください。この issue ではファイル、テスト、実装のエントリーポイントが指定されておらず、完了するには、この動作をサポートすべきかどうか、またどのように仕様化すべきかを決める必要があります。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- devtools
- issue の種類
- 機能追加
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 活発さ
- 停滞
- 明瞭さ
- 説明が足りない
- 初心者へのやさしさ
- 20/100