Skip to content

RUF024 fix shadows a variable named key #24304

@dscorbett

Description

@dscorbett

Summary

The fix for mutable-fromkeys-value (RUF024) changes the program’s behavior when the second argument to dict.fromkeys uses a variable named key because the fix creates a new key that shadows it. The best solution is for Ruff to use a gensym-like function to try e.g. key then key_0, key_1, etc. until it finds an unused name. This would benefit all fixes that create new variables. Example:

$ cat >ruf024.py <<'# EOF'
key = "xy"
print(dict.fromkeys("ABC", list(key)))
# EOF

$ python ruf024.py
{'A': ['x', 'y'], 'B': ['x', 'y'], 'C': ['x', 'y']}

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

$ cat ruf024.py
key = "xy"
print({key: list(key) for key in "ABC"})

$ python ruf024.py
{'A': ['A'], 'B': ['B'], 'C': ['C']}

Version

ruff 0.15.8 (c2a8815 2026-03-26)

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