[match-case]: `TypedDict` interaction with mapping pattern
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 1.8k
- Fork
- 302
- Merge medio
- 23h
- PR unite (30g)
- 8
Descrizione
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.
Guida per i contributori
Nessuna guida per i contributori indicizzata per questo repository
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia dalla sezione sul TypedDict subtyping-with-mapping della typing specification e dalle regole dei mapping patterns di PEP 634. Esegui i tre esempi con i type checker elencati per confrontare il comportamento attuale. Il lavoro è completato quando si raggiunge un accordo sul narrowing previsto e si documenta una guida standardizzata, con i corrispondenti casi di validazione.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- devtools
- Tipo di issue
- Funzionalità
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100