Hacktoberfest 2026: as issues que os mantenedores marcaram para outubro, abertas e boas para iniciantes. Ver issues do Hacktoberfest

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

Aberta
#2,185 1 comentário 0 reações 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
5/5
Tempo estimado
Mais de uma semana
Facilidade para iniciantes
35/100
Tipo de issue
Funcionalidade
Clareza
Razoavelmente clara
Status de atividade
Estagnada
Stack de tecnologia
python
Domínio
devtools

Direção de pesquisa

Comece pela seção sobre TypedDict subtyping-with-mapping da typing specification e pelas regras de mapping patterns da PEP 634. Execute os três exemplos com os type checkers listados para comparar o comportamento atual. O trabalho estará concluído quando houver concordância sobre o narrowing pretendido e uma orientação padronizada for documentada, com os casos de validação correspondentes.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

topic: feature

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.

Linguagem predominante
Python
Estrelas
1.8k
Forks
302
Merge médio
23h
PRs com merge (30d)
8

Guia de contribuição

Nenhum guia de contribuição indexado para este repositório

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de python/typing

Todas as issues de python/typing

Issues semelhantes

Mais issues de Python

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.