Skip to content

PERF401 false positive when a target variable is global or nonlocal #19531

@dscorbett

Description

@dscorbett

Summary

The fix for manual-list-comprehension (PERF401) is incorrect when the for loop’s target list includes a global or nonlocal variable. Rewriting the loop with a comprehension means the variable isn’t updated. This is similar to #16445. Example:

$ cat >perf401.py <<'# EOF'
INDEX = None
def f():
    global INDEX
    result = []
    for INDEX in range(3):
        result.append(+INDEX)
f()
print(INDEX)
# EOF

$ python perf401.py
2

$ ruff --isolated check perf401.py --select PERF401 --preview --unsafe-fixes --fix
Found 1 error (1 fixed, 0 remaining).

$ cat perf401.py
INDEX = None
def f():
    global INDEX
    result = [+INDEX for INDEX in range(3)]
f()
print(INDEX)

$ python perf401.py
None

Version

ruff 0.12.5 (d13228a 2025-07-24)

Metadata

Metadata

Assignees

Labels

bugSomething isn't workingfixesRelated to suggested fixes for violations

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions