MartinThoma / flake8-simplify

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

[New Rule] Factor out common code from if branches #117

Open TomFryers opened 2 years ago

TomFryers commented 2 years ago

Explanation

This can make the code much less repetitive. It would be nice to do this with common code at the start of each branch, but this could be problematic if it affects the if expressions (although that shoudn’t be that common).

Maybe this could also apply to match statements. In both cases, there are easy-to-check sufficient conditions for exhaustiveness.

Example

# Bad
if x == 3:
   print("foo")
   print("bar")
elif x == 4:
   print("foo5000")
   print("bar")
else:
   print("foobar")
   print("bar")

# Good
if x == 3:
   print("foo")
elif x == 4:
   print("foo5000")
else:
   y = 5
   print("foobar")
print("bar")
TomFryers commented 1 year ago

This could also apply to ternary operators, as in

# Bad
y = f(x) if x > 2 else f(3 + x)

# Good
y = f(x if x > 2 else 3 + x)