python / python/mypy

“Cannot infer type of lambda” using default parameter to recapture loop variable

Aperta
#15,459 2 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug topic-inference
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

Bug Report

One of the most common gotchas in Python is that a loop reassigns its iteration variable rather than creating a new binding for each iteration, and a lambda closure created in the loop observes this reassigned value rather than the value from each iteration. A typical workaround is to add a “redundant” default parameter to the lambda to recapture the value from each iteration—for example, the i=i from the above link (reproduced below). But mypy rejects such a lambda with error: Cannot infer type of lambda [misc].

To Reproduce

from typing import Callable

def create_multipliers() -> list[Callable[[int], int]]:
    return [lambda x, i=i: i * x for i in range(5)]

(mypy playground)

Expected Behavior

mypy ought to be able to realize that since the lambda is coerced to Callable[[int], int], its second parameter i=i can only ever receive the default value, so its type should be successfully inferred as (x: int, i: int = ...) -> int.

Actual Behavior

main.py:4: error: Cannot infer type of lambda  [misc]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.3.0
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.11.3

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 eseguendo la riproduzione main.py con mypy e verificando come vengono inferiti i tipi dei parametri lambda e delle espressioni predefinite per il contesto Callable[[int], int]. Segui il punto di ingresso rilevante dell'inferenza dei tipi e aggiungi un test di regressione per l'esempio; il lavoro è completato quando mypy accetta il codice senza Cannot infer type of lambda, mantenendo la firma callable inferita.

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.