Skip to content

New rule: Prefer in-place operators #8877

@Avasam

Description

@Avasam

I don't think any linter currently checks for this, although I did open a feature request in those I knew of where this feature might be in scope (MartinThoma/flake8-simplify#188 and dosisod/refurb#310). Whether they accept it, (and who knows when it would be implemented), this is still a check I'd like to see in Ruff as I don't directly use those other linters and autofixing should be possible. If you think this is a viable rule.

In-place operators lead to more concise code that is still readable. I'm not sure if there's any objective drawbacks (like a common pitfall for certain types). And performance-wise my understanding is that it should be faster (due to the in-place nature) or equivalent (thanks to Python duck-typing that will fallback to __add__ if __iadd__ is not implemented).

Any of the following:

some_string = (
  some_string
  + "a veeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeery long end of string"
)
index = index - 1
a_list = a_list + ["to concat"]
some_set = some_set | {"to concat"}
to_multiply = to_multiply * 5
to_divide = to_divide / 5
to_cube = to_cube ** 3
timeDiffSeconds = timeDiffSeconds % 60
flags = flags & 0x1
# etc.

Could be re-written as:

some_string += "a veeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeery long end of string"
index -= 1
a_list += ["to concat"]
some_set |= {"to concat"}
to_multiply *= 5
to_divide /= 5
to_cube **= 3
timeDiffSeconds %= 60
flags &= 0x1
# etc.

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedContributions especially welcomeruleImplementing 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