MartinThoma / flake8-simplify

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

[Adjust Rule] SIM109 - Do not suggest rewrites when comparing against function calls #76

Closed mxr closed 2 years ago

mxr commented 2 years ago

Desired change

Explanation

The check a == b or a== c or ... allows short-circuiting. But the suggested rewrite evaluates all the values we're comparing against, which can have non-trivial performance implications.

Example

def compute1() -> int:
    """imagine this function makes an expensive computation"""
    pass

def compute2() -> int:
    """imagine this function makes an expensive computation"""
    pass

x = int(input("Enter a num: "))
print(x == compute1() or x == compute2())

The suggested rewrite is

$ flake8 example.py 
example.py:12:7: SIM109 Use 'x in [compute1(), compute2()]' instead of 'x == compute1() or x == compute2()'

That suggestion would cause compute2() to always be evaluated even if it's not always necessary

Recommendation

Only suggest a rewrite when the value to compare against is not a function call

MartinThoma commented 2 years ago

Ah, damn, I didn't think about that case. I tend to think about functions as being cachable, but this is obviously not the case. Network traffic would be another example.