python / python/mypy

--possibly-undefined misses for-loop conditional definitions

Open
#16,050 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked mypy-play reproduction and the --enable-error-code possibly-undefined flag to confirm the missing warning for an empty iterable. Trace the relevant for-loop flow analysis, add a regression test for the conditional definition case, and verify that mypy reports the expected possibly-undefined error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.