python / python/mypy

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

Aperta
#10,752 9 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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?

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia con gli esempi di overload nell’issue e traccia il modo in cui mypy seleziona tra un overload simile a SomeType[Any] e un overload Any. Confronta il caso Callable/Any con i casi int/Any e Callable/int, quindi verifica che il comportamento corretto segnali l’assegnazione incompatibile preservando al contempo i casi contrastanti esistenti.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
devtools
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.