python / python/mypy

--possibly-undefined misses for-loop conditional definitions

Aperta
#16,050 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

Bug Report

--enable-error-code possibly-undefined does not detect when a local variable is conditionally set by a for loop.

To Reproduce

https://gist.github.com/mypy-play/25a51361be6d697e25b32587e4cba351
https://mypy-play.net/?mypy=latest&python=3.11&gist=25a51361be6d697e25b32587e4cba351

Expected Behavior

If a variable is set by a for loop over an iterable (i.e. for x in l), and

  • that variable was not previously initialized
  • the iterable may be empty

then mypy should warn against a UnboundLocalError that would be raised by accessing that variable after the loop, were that iterable to be empty.

Actual Behavior

mypy reports no issues.

A workaround is to wrap the for loop with an if condition to check if the iterable being looped over is not empty.

For example:

if l:
  for x in l:
    # ...

Your Environment

  • Mypy version used: 1.5.1
  • Mypy command-line flags: --enable-error-code possibly-undefined
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.11.4

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 la riproduzione collegata di mypy-play e il flag --enable-error-code possibly-undefined per confermare che manca l’avviso per un iterable vuoto. Traccia l’analisi di flusso rilevante del for-loop, aggiungi un test di regressione per il caso di definizione condizionale e verifica che mypy segnali l’errore possibly-undefined previsto.

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

Valutazione

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

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.