[match-case]: `TypedDict` interaction with mapping pattern
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 1.8k
- フォーク
- 302
- 平均マージ
- 23時間
- マージ済み PR(30日)
- 8
説明
It seems match-cases mapping pattern is predestined to work well with TypedDict, but currently the spec is silent regarding TypedDict subtyping with respect to match case: https://typing.python.org/en/latest/spec/typeddict.html#subtyping-with-mapping
At the time of writing, not a single type checker (tested with mypy=1.19.1, pyright=1.1.408, ty=0.0.17, pyrefly=0.53.0 and zuban=0.6.0) can solve the following tests[^1], suggesting that some standardization / typing spec guidance may be useful.
from typing import TypedDict, assert_type, assert_never
class D(TypedDict):
name: str
value: int
def test_match_key(x: D | int) -> None:
match x:
case {"name": _}:
# runtime equivalent to (isinstance(x, Mapping) and "name" in x)
assert_type(x, D)
case _:
assert_type(x, int)
def test_match_key_and_value(x: D | int) -> None:
match x:
case {"name": str()}:
# runtime equivalent to (isinstance(x, Mapping)
# and "name" in x and isinstance(x["name"], str))
assert_type(x, D)
case _:
assert_type(x, int)
def test_non_match(x: D | int) -> None:
match x:
case {"value": str()}:
# runtime equivalent to (isinstance(x, Mapping)
# and "value" in x and isinstance(x["value"], str))
assert_never(x)
case _:
assert_type(x, D | int)
[^1]: technically, it is possible to make a shared subclass of int and collections.abc.Mapping, so the assert_type in the case {...} are debatable, though the inference in the case _ branches should not be affected.
コントリビューションガイド
このリポジトリのコントリビューションガイドは索引されていません
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
typing specification の TypedDict subtyping-with-mapping セクションと、PEP 634 の mapping-pattern ルールから始めてください。現在の挙動を比較するため、一覧にある type checker で 3 つの例を実行してください。意図された narrowing について合意に達し、対応する検証ケースとともに標準化されたガイダンスを文書化できれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- devtools
- issue の種類
- 機能追加
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 35/100