Skip to content

For loop variable scope issue #9576

@Harmos274

Description

@Harmos274

Bug Report

When you create two or more for x in y loop, if the xs are same-named, mypy raise a Incompatible types in assignment error.

To Reproduce

  1. Code sample
# file: main.py

from typing import List

def main() -> None:
    vector: List[str] = list()
    matrix: List[List[str]] =  [["0" for i in range(len(vector))] for y in range(len(vector))]

    for line in vector: # first loop
        print(line)

    for line in matrix: # second loop
        print(line)
    
main()
  1. Mypy
$> mypy ./main.py

Expected Behavior
The "line" variables exists only in the scope of their for loops, so it shouldn't be an error for mypy.

Actual Behavior

main.py:12: error: Incompatible types in assignment (expression has type "List[str]", variable has type "str")
Found 1 error in 1 file (checked 1 source file)

It seems that mypy consider the two "line" variables as one and raise an error.

My Environment

  • Mypy version used: mypy 0.782
  • Python version used: Python 3.8.5
  • Operating system and version: Fedora 32

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions