Skip to content

PERF401 fix should parenthesize generator expressions #19204

@dscorbett

Description

@dscorbett

Summary

The fix for manual-list-comprehension (PERF401) changes the program’s behavior when the argument to append is an unparenthesized generator expression. It should parenthesize the argument. Example:

$ cat >perf401.py <<'# EOF'
i = "xyz"
result = []
for i in range(3):
   result.append(x for x in [i])
print(list(map(list, result)))
# EOF

$ python perf401.py
[[0], [1], [2]]

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

$ cat perf401.py
i = "xyz"
result = [x for x in [i] for i in range(3)]
print(list(map(list, result)))

$ python perf401.py
[['x', 'y', 'z'], ['x', 'y', 'z'], ['x', 'y', 'z']]

Version

ruff 0.12.2 (9bee837 2025-07-03)

Metadata

Metadata

Assignees

Labels

bugSomething isn't workingfixesRelated to suggested fixes for violationshelp wantedContributions especially welcome

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions