Skip to content

C416 incorrectly flags dict comprehension based on dict with tuple keys #13625

@henribru

Description

@henribru

https://play.ruff.rs/4d78b865-9778-415b-9303-377a3fdff673

d1 = {(1, 2): 3, (3, 4): 5}
d2 = {x: y for x, y in d1}

C416 suggests changing d2 to dict(d1), which is incorrect because this will just copy d1.

This seems like an intractable problem to solve in general because you'd have to know whether the thing being iterated over is a dict. In a case like this I suppose it could be done with local type inference, though. SIM118 mentions acting differently based on whether it can statically know something to be a dict, so I assume that's something Ruff is already capable of.

The fix is thankfully already marked as unsafe for a different reason, so this isn't a huge problem. But it seems worth documenting this case as another reason for marking it as unsafe.

Metadata

Metadata

Assignees

No one assigned

    Labels

    ruleImplementing or modifying a lint ruletype-inferenceRequires more advanced type inference.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions