Cannot infer type of lambda when using default arguments
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
Bug Report
I get error: Cannot infer type of lambda even though the code seems fine to me.
Currently, I don't see any other workaround other than using # type: ignore.
To Reproduce
from typing import Callable, List
def foo(factories: List[Callable[[], int]]):
return sum(f() for f in factories)
names = ["0", "abc"]
# Inference works fine
assert foo([lambda: len(name) for name in names]) == 4
# Cannot infer type of lambda
assert foo([lambda name=name: len(name) for name in names]) == 4
def foo2(factories: List[Callable[[int], int]]):
return sum(f(0) for f in factories)
# Inference works fine
assert foo2([lambda i: len(name) for name in names]) == 4
# Cannot infer type of lambda
assert foo2([lambda i, name=name: len(name) for name in names]) == 4
Checked with:
mypy mypy-lambda-test.py
Expected Behavior
There should be no error. Especially because the other variants without default arguments are deemed fine.
Furthermore, using default arguments like this is the standard workaround to capture loop variables to lambdas.
Your Environment
- Mypy version used: 0.942
- Python version used: 3.9.7
- Operating system and version: Ubuntu 21.10
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 con gli esempi lambda in mypy-lambda-test.py ed esegui mypy mypy-lambda-test.py usando le versioni indicate di Python e mypy. Confronta le lambda funzionanti con le varianti che catturano name tramite un argomento predefinito. Il lavoro è completato quando tutte e quattro le asserzioni superano il controllo dei tipi senza richiedere # type: ignore.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- tooling
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100