Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Enhancement]: Rule to prefer in-place operators #310

Open
Avasam opened this issue Nov 28, 2023 · 2 comments
Open

[Enhancement]: Rule to prefer in-place operators #310

Avasam opened this issue Nov 28, 2023 · 2 comments
Labels
enhancement New feature or request

Comments

@Avasam
Copy link

Avasam commented Nov 28, 2023

Overview

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). Relates to #28

Proposal

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.
@dosisod
Copy link
Owner

dosisod commented Dec 1, 2023

Thank you for opening this! This sounds easy enough to implement, I'll give it a shot over the weekend.

Because anyone can make their own custom in-place operators, I think it is best to only support built-in types, though there should be an option to extend this to all types once I add option support (see #100).

Also, I'd probably add these to your list as well:

a = a or b
c = c and d

Re-write as:

a |= b
c &= d

assuming a, b, c and d are bool types.

@pums974
Copy link

pums974 commented Dec 1, 2023

Hi,

I'm sure you are considering it, but allow me this warning.

For mutable types, inplace operators are not equivalent to normal operators for exemple:

a=[]
b=a
a+= [1]
a= a+[2]
print(a,b) # [1,2] [1]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants