Overloading a function with a parameter that can be either SomeType[Any] or Any always results in the return type Any
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
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?
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
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.
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
- 35/100