python / python/typing

[match-case]: `TypedDict` interaction with mapping pattern

Abierto
#2,185 1 comentario 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

topic: feature
Lenguaje dominante
Python
Estrellas
1.8k
Forks
302
Merge medio
23 h
PR fusionados (30 d)
8

Descripción

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.

Guía de contribución

No hay ninguna guía de contribución indexada para este repositorio

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza con la sección sobre TypedDict subtyping-with-mapping de la typing specification y las reglas de mapping patterns de PEP 634. Ejecuta los tres ejemplos con los comprobadores de tipos indicados para comparar el comportamiento actual. Se considera terminado cuando se haya llegado a un acuerdo sobre el estrechamiento previsto y se haya documentado una guía estandarizada, junto con los casos de validación correspondientes.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
python
Área
devtools
Tipo de issue
Nueva funcionalidad
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.