CodeQL documentation

Nested loops with same variable

ID: py/nested-loops-with-same-variable
Kind: problem
Severity: recommendation
Precision: very-high
Tags:
   - maintainability
   - correctness
Query suites:
   - python-security-and-quality.qls

Click to see the query in the CodeQL repository

In Python variables have function-wide scope which means that if two variables have the same name in the same scope, they are in fact one variable. Consequently, nested loops in which the target variables have the same name in fact share a single variable. Such loops are difficult to understand as the inner loop will modify the target variable of the outer loop; this may be a typographical error.

Recommendation

Carefully examine the code and check for possible errors, particularly considering what would happen if the inner or outer variable were renamed.

Example


for var in range(3):
    for var in range(3):
        pass
    print (var) # Prints 2 2 2 not 0 1 2 as might be expected

References