python / python/mypy

Error for lambda containing Any even when type can be inferred

Offen
#5,879 4 Kommentare 3 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug false-positive priority-0-high topic-disallow-any topic-usability
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Using mypy 0.641 with the --disallow-any-expr flag and this sample using @overload

from typing import Callable, Tuple, TypeVar, overload

T = TypeVar('T')
A0 = TypeVar('A0')
A1 = TypeVar('A1')


@overload
def foo(
    vars: Tuple[A0],
    op: Callable[[A0], T]
) -> T: ...


@overload
def foo(
    vars: Tuple[A0, A1],
    op: Callable[[A0, A1], T]
) -> T: ...


def foo(vars, op):
    pass


def foo_not_overloaded(
    vars: Tuple[A0, A1],
    op: Callable[[A0, A1], T]
) -> T:
    pass


a = 5
b = 3

foo((a, b), lambda a, b: a - b)

produces

typist2.py:36: error: Expression type contains "Any" (has type "Callable[[Any, Any], Any]")
typist2.py:36: error: Expression has type "Any"

However mypy seems to be able to infer the type of the lambda because if I modify the last line to read

foo((a, b), lambda a, b: a - b.bad)

mypy correctly identifies that "int" has no attribute "bad", sprinkling some prints on the mypy source also reveals it figures out it's a (int, int) -> int at some point.

foo_not_overloaded checks without trouble and so does using a plain def instead of the lambda.

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginnen Sie mit dem bereitgestellten Reproducer unter Verwendung von mypy 0.641 und vergleichen Sie den überladenen foo-Aufruf mit foo_not_overloaded und dem Fall mit einem einfachen def. Verfolgen Sie den inferierten Typ des Lambdas durch den Overload-Pfad und überprüfen Sie anschließend, dass das gültige Lambda keine disallow-any-expr-Fehler mehr auslöst, während die Variante a - b.bad weiterhin das ungültige Attribut meldet.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
compilers
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
35/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.