Overloading a function with a parameter that can be either SomeType[Any] or Any always results in the return type Any

Offen
#10,752 9 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

Bewertung

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

Rechercherichtung

Beginne mit den Overload-Beispielen im Issue und verfolge, wie mypy zwischen einem SomeType[Any]-ähnlichen Overload und einem Any-Overload auswählt. Vergleiche den Fall Callable/Any mit den Fällen int/Any und Callable/int und überprüfe anschließend, dass das korrigierte Verhalten die inkompatible Zuweisung meldet und dabei die bestehenden kontrastierenden Fälle beibehält.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Beschreibung

Edit: I initially observed this behaviour for Callable[..., Any] and Any, but it now seems like this happens for any SomeType[Any] and Any, hence we've edited the title. For a more extensive explanation, scroll down to post 8.


I noticed that overloading a function with a Callable / Any parameter doesn't work as I'd expect. For example:

from typing import Any, Callable, overload

@overload
def foo(a: Callable) -> int: ...
@overload
def foo(a: Any) -> Any: ...

def foo(a):
    pass

a: str = foo(lambda x: x)

I'd expect the mypy error Incompatible types in assignment (expression has type "int", variable has type "str"), but there's no error here.

Of note, if I replace Callable by something else, it works fine:

from typing import Any, overload

@overload
def foo(a: int) -> int: ...
@overload
def foo(a: Any) -> Any: ...

def foo(a):
    pass

a: str = foo(1)
# mypy error: Incompatible types in assignment (expression has type "int", variable has type "str")

Finally, if I instead replace Any by something else, it also works fine.

from typing import Any, Callable, overload

@overload
def foo(a: Callable) -> int: ...
@overload
def foo(a: int) -> Any: ...

def foo(a):
    pass

a: str = foo(lambda x: x)
# mypy error: Incompatible types in assignment (expression has type "int", variable has type "str")

So it only doesn't work as expected in the first code block. Is that a bug? Or is it expected behaviour somehow?

Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
Ø Merge
1 T. 18 Std.
Gemergte PRs (30 T.)
54

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lesen Sie das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreiben Sie ins Issue, dass Sie es übernehmen — das erspart doppelte Arbeit.
  3. Forken Sie das Repository und arbeiten Sie in einem Branch.
  4. Öffnen Sie einen Pull Request, der die Issue-Nummer nennt.

Mehr aus python/mypy

Alle Issues in python/mypy

Ähnliche Issues

Weitere Issues zu Python

Neue Issues direkt in Ihr Postfach

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