MartinThoma / flake8-simplify

❄ A flake8 plugin that helps you to simplify code
MIT License
185 stars 19 forks source link

[New Rule] Preferring in-place operators #188

Open Avasam opened 9 months ago

Avasam commented 9 months ago

Explanation

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 pitfalls 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).

Example

# Bad
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.

# Good
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.