Skip to content

Allow Redefinitions of For Loop Iteration Variables #15988

@rameshvarun

Description

@rameshvarun

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions