DefaultDict of a TypedDict confuses mypy
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
Hi 👋 ! I have the following test code:
from collections import defaultdict
from typing import DefaultDict
from mypy_extensions import TypedDict
RepoPath = str
RepoStatus = TypedDict('RepoStatus', {
'branch': str,
'remote': str,
'clean': bool,
# ...
}, total=False)
State2 = defaultdict(RepoStatus) # type: DefaultDict[RepoPath, RepoStatus]
State3 = defaultdict(dict) # type: DefaultDict[RepoPath, RepoStatus]
State4 = defaultdict(lambda: RepoStatus()) # type: DefaultDict[RepoPath, RepoStatus]
State5 = defaultdict(lambda: dict()) # type: DefaultDict[RepoPath, RepoStatus]
State6 = defaultdict(lambda: {}) # type: DefaultDict[RepoPath, RepoStatus]
mypy only accepts the definition of 4 and 6. A pic is easy to follow here

mypy output:
16:10 error mypy Argument 1 to "defaultdict" has incompatible type "Type[RepoStatus]"; expected
"Optional[Callable[[], RepoStatus]]"
17:10 error mypy Argument 1 to "defaultdict" has incompatible type "Type[Dict[Any, Any]]";
expected "Optional[Callable[[], RepoStatus]]"
19:10 error mypy Argument 1 to "defaultdict" has incompatible type "Callable[[], Dict[<nothing>,
<nothing>]]"; expected "Optional[Callable[[], RepoStatus]]"
19:22 error mypy Incompatible return value type (got "Dict[<nothing>, <nothing>]", expected
"RepoStatus")
Ideally the def of State3, just defaultdict(dict), should work, shouldn't it? It is also very surprising that there is a difference between 5 and 6.
mypy 0.720
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 lo snippet State2–State6 dell’issue con mypy 0.720 e confronta le diagnosi per ogni forma di defaultdict. Traccia come vengono inferiti gli argomenti del costruttore di defaultdict e i tipi restituiti da TypedDict; il lavoro è completato quando le forme previste vengono verificate dal type checker in modo coerente e la differenza inattesa tra State5 e State6 viene risolta o documentata tramite test.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- devtools
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 42/100