Skip to content

Dictionary update operator mutates input #336

Open
@danhje

Description

@danhje

Sourcery wants to refactor d = d | {"add": "this"} into d |= {"add": "this"}, but the two are not equivalent. The latter actually mutates d, while the first creates a new dict and assigns it to the same variable.

def add_b(d: dict) -> dict:
    d = d | {"b": 2}
    return d

def add_c(d: dict) -> dict:
    d |= {"c": 3}
    return d

original = {"a": 1}

updated = add_b(original)
assert original == {"a": 1}  # All good

updated = add_c(original)
assert original == {"a": 1}  # Error, original is now {"a": 1, "c": 3}

I suggest removing the refactoring.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingnext releaseThis will be fixed in next release

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions