Narrowing argument types based on overload variants
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
Feature
Currently mypy cannot narrow down argument types in a function implementation based on function's overload variants. The following code
@overload
def f(x: None, y: None) -> None:...
@overload
def f(x: str, y: int) -> int:...
def f(x: Optional[str], y: Optional[int]) -> Optional[int]:
if x is not None:
return len(x) + y # error: Unsupported operand types for + ("int" and "None")
else:
return None
results in a Unsupported operand types for + ("int" and "None")" error. Despite of the fact that f() can be called only with either (None, None) or (str, int) which is specified by the respective overloads, mypy cannot infer that if the first argument is not None, then the other argument also shouldn't be None.
Here is my use case where I find this inference would be helpful:
class A:
pass
class B:
pass
class C:
pass
class D:
pass
@overload
def f(x: A) -> C:...
@overload
def f(x: B) -> D:...
def f(x: Union[A, B]) -> Union[C, D]:
if isinstance(x, A):
return C()
else:
return D()
@overload
def g(x: A, func: Callable[[C], bool]) -> None:...
@overload
def g(x: B, func: Callable[[D], bool]) -> None:...
def g(x: Union[A, B], func: Union[Callable[[C], bool], Callable[[D], bool]]) -> None:
obj = f(x)
func(obj) # error: Argument 1 has incompatible type "Union[C, D]"; expected "C"
Without being able to infer that when x is an instance of A, func should be an instance of Callable[[C], bool] (which is specified by the overload variants), mypy results in the following error:
test.py:37: error: Argument 1 has incompatible type "Union[C, D]"; expected "C"
test.py:37: error: Argument 1 has incompatible type "Union[C, D]"; expected "D"
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia riproducendo il problema con gli esempi di overload riportati e verifica come mypy gestisce le varianti di overload, il narrowing degli argomenti e il controllo del corpo dell'implementazione. Il lavoro è completato quando le implementazioni mostrate non segnalano più gli errori «incompatible-operand» e «incompatible-call», preservando al contempo il comportamento di overload dichiarato.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- compilers, devtools
- Tipo di issue
- Funzionalità
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100