Mypy can't infer parameter types for nested function calls.
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
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
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginnen Sie damit, den gemeldeten Fehler mit dem verschachtelten itertools.starmap- und filter-Beispiel unter Verwendung von mypy 0.761 zu reproduzieren. Verfolgen Sie, wie Argumenttypen durch die beiden Aufrufe inferiert werden, und vergleichen Sie das Ergebnis mit der Version mit explizitem Cast. Die Aufgabe ist abgeschlossen, wenn das ursprüngliche Beispiel den fälschlicherweise gemeldeten Iterable[Any]-Indexierungsfehler nicht mehr meldet, ohne einen Cast zu erfordern.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 25/100