DefaultDict of a TypedDict confuses mypy
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Python
- Estrellas
- 20.6k
- Forks
- 3.3k
- Métricas de merge de PR
- Métricas de PR pendientes
Descripción
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
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
Comienza reproduciendo el fragmento State2–State6 del issue con mypy 0.720 y compara los diagnósticos para cada forma de defaultdict. Rastrea cómo se infieren los argumentos del constructor de defaultdict y los tipos de retorno de TypedDict; se considera terminado cuando las formas previstas pasan la comprobación de tipos de manera consistente y la diferencia inesperada entre State5 y State6 se resuelve o se documenta mediante pruebas.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- python
- Área
- devtools
- Tipo de issue
- Error
- Dificultad
- 4/5
- Tiempo estimado
- 3-5 días
- Estado de actividad
- Estancado
- Claridad
- Bastante claro
- Aptitud para principiantes
- 42/100