python / python/mypy

Allow Redefinitions of For Loop Iteration Variables

Open
#15,988 2 comments 3 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

MyPy has a flag --allow-redefinition to enable variable redefinition in limited circumstances. This doesn't seem to work with variables bound in a for loop iteration.

To Reproduce

https://mypy-play.net/?mypy=1.5.1&python=3.11&flags=allow-redefinition&gist=005972804edd5316ace18ea835fb9f52

for i in range(3):
    i: str = str(i)
    reveal_type(i)
    
def test(i: int):
    i: str = str(i)
    reveal_type(i)

Expected Behavior

Both cases are allowed.

Actual Behavior

MyPy throws an error only for line 2.

main.py:2: error: Name "i" already defined on line 1  [no-redef]
main.py:3: note: Revealed type is "builtins.int"
main.py:7: note: Revealed type is "builtins.str"
Found 1 error in 1 file (checked 1 source file)

Your Environment

MyPy Version v1.5.1

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 by running the linked mypy-play reproduction with MyPy 1.5.1, the Python 3.11 example, and --allow-redefinition. Trace how the for-loop variable and the function parameter are handled, then add coverage showing both redefinitions are accepted and the revealed types match the expected output.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 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.