Skip to content

C420 false positive when the assignment mutates a pre-existing object #19511

@dscorbett

Description

@dscorbett

Summary

unnecessary-dict-comprehension-for-iterable (C420) has a false positive when the assignment target includes an attribute reference, subscription, or slicing. The assignment has a side effect beyond the comprehension so the comprehension is not unnecessary. Example:

$ cat >c420.py <<'# EOF'
class C: a = None
{C.a: None for C.a in "abc"}
print(C.a)

x = [None]
{x[0]: None for x[0] in "abc"}
print(x)

class C(list):
    def __getitem__(self, index, /):
        item = super().__getitem__(index)
        if isinstance(index, slice): item = tuple(item)
        return item
x = C()
{x[:0]: None for x[:0] in "abc"}
print(x)
# EOF

$ python c420.py
c
['c']
['c', 'b', 'a']

$ ruff --isolated check c420.py --select C420 --preview --fix
Found 3 errors (3 fixed, 0 remaining).

$ python c420.py
None
[None]
[]

Version

ruff 0.12.4 (ee2759b 2025-07-17)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingruleImplementing or modifying a lint rule

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions