type inference is fragile for protocols like SupportsKeysAndGetItem
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
Repro: https://mypy-play.net/?mypy=latest&python=3.11&gist=d2f8dfa1fdfda5c0c286f1a73f5e39eb
Pasted below for convenience:
import typing as t
from _typeshed import SupportsKeysAndGetItem
KT = t.TypeVar("KT")
VT = t.TypeVar("VT")
def version1(obj: SupportsKeysAndGetItem[KT, VT] | t.Iterable[tuple[KT, VT]]):
if hasattr(obj, "keys") and hasattr(obj, "__getitem__"):
reveal_type(obj) # SupportsKeysAndGetItem[KT, VT] | Iterable[tuple[KT, VT]] (as expected)
else:
reveal_type(obj) # narrowed to Iterable[tuple[KT, VT]] as expected
def version2(obj: SupportsKeysAndGetItem[KT, VT] | t.Iterable[tuple[KT, VT]]):
if hasattr(obj, "keys") and hasattr(obj, "__getitem__") and (obj_getitem := obj.__getitem__):
reveal_type(obj) # SupportsKeysAndGetItem[KT, VT] | Iterable[tuple[KT, VT]] (as expected)
else:
reveal_type(obj) # NOT narrowed
I would expect version 2 to behave the same as version 1. Is that an improvement mypy could reasonably make?
I searched for relevant docs and existing issues, but didn't find anything specifically about this. Apologies if I missed something.
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
Esegui la riproduzione collegata di mypy-play e confronta i risultati di reveal_type in version1 e version2. Traccia la logica del restringimento dei tipi per i controlli combinati hasattr e l’assegnazione con walrus; il lavoro è completo quando version2 restringe il ramo else in modo coerente con version1, con una copertura di regressione per l’esempio.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- compilers, devtools
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Tranquilla
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 48/100