Mypy can't infer parameter types for nested function calls.
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
I'm trying to run mypy against this code
import itertools
itertools.starmap(
lambda x, y: True, filter(lambda in_deg: in_deg[1],
[(1, 2)]))
I get the following error message:
error: Value of type "Iterable[Any]" is not indexable
It seems like mypy is starting type inference from the outside and inward, so it starts with itertools.starmap. The first callable is considered to take arguments resulting from the unpacking of an iterable: Iterable[Any], hence the second argument is considered Iterable[Iterable[Any]]. Since the second argument to itertools.starmap here is a function call to filter, it's assumed that filter must return Iterable[Iterable[Any]] to match the second argument expected by itertools.starmap. This coerces the second argument to filter to be seen as Iterable[Iterable[Any]], which in turn coerces the first argument to filter to be seen as a callable taking Iteable[Any]. This overlooks the explicitly obvious fact here that the second argument to filter is actually List[Tuple[int, int]](or at worst Iterable[Tuple[int, int]]) which will cause the first filter argument to be a callable that takes Tuple[int, int], effectively suppressing the spurious error.
One way to overcome this misinterpretation of the argument types is to explicitly cast the result of filter to be Iterable[Tuple[int, int]], which will rightfully suppress the error.
import itertools
import typing
itertools.starmap(
lambda x, y: True, typing.cast(typing.Iterable[typing.Tuple[int, int]],
filter(lambda in_deg: in_deg[1], [(1, 2)])))
mypy version: 0.761
python version: 3.7.6
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 error reportado con el ejemplo anidado de itertools.starmap y filter usando mypy 0.761. Traza cómo se infieren los tipos de los argumentos a través de las dos llamadas y compara el resultado con la versión con cast explícito. Se considera terminado cuando el ejemplo original ya no informa del error espurio de indexación de Iterable[Any] sin requerir un cast.
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
- 25/100