Exhaustiveness checking fails on non-trivial use of pattern matching
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 20.6k
- Fork
- 3.3k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
Code using assert_never() to ensure exhaustive use of match-case yields a type error on many non-trivial cases.
mypy can only verify exhaustiveness when matching directly against a Union type or Enum value.
Though, proving the exhaustiveness of non-trivial matches may be beyond mypy domain. Here are a couple of examples for the sake of argument:
Matching on both [] and [x, *xs] on Sequence will not narrow the type
from collections.abc import Sequence
from typing import assert_never
def my_sum(s: Sequence[float]) -> float:
match s:
case []:
return 0
case [num, *rest]:
return num + my_sum(rest)
case _ as u:
# error: Argument 1 to "assert_never" has incompatible type "Sequence[float]"; expected "NoReturn"
return assert_never(u)
Matching against all Enum values that a single-member wrapper class may contain
import dataclasses, enum
from typing import assert_never, final
class E(enum.Enum):
A = enum.auto()
B = enum.auto()
@final
@dataclasses.dataclass(frozen=True)
class Foo:
x: E
def match_enum_attribute(f: Foo) -> None:
match f:
case Foo(E.A):
pass
case Foo(E.B):
pass
case _ as r:
# error: Argument 1 to "assert_never" has incompatible type "Foo"; expected "NoReturn" [arg-type]
assert_never(r)
Guida per i contributori
Apri la guida per i contributori
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 riproducendo i due esempi usando assert_never(), match-case, pattern Sequence e l’attributo Enum wrapped mostrato nell’issue. Traccia il comportamento di exhaustiveness e narrowing di mypy per questi casi; il lavoro è completo quando i match non banali supportati vengono riconosciuti come esaustivi senza gli errori di tipo segnalati, con la copertura per gli esempi.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- devtools
- Tipo di issue
- Bug
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Stato di attività
- Tranquilla
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100