pylint icon indicating copy to clipboard operation
pylint copied to clipboard

Suggest flattening nested idempotent function applications

Open l0b0 opened this issue 4 months ago • 3 comments

Current problem

Expressions with multiple applications of the same idempotent function can often (depending on side effects between applications) be flattened to a single application. This might simplify the code and make it use less resources.

Desired solution

Pylint should suggest simplifying such applications. Examples:

  • min(min(a, b)) can be simplified to min(a, b).

  • A more complex example involving variable reuse might suggest that

    first = min(a, b)
    second = min(c, d)
    first = min(first, second)
    

    can be simplified to

    second = min(c, d)
    first = min(a, b, second)
    

    if second is used later in the code or

    first = min(a, b, c, d)
    

    if second is not used later.

Additional context

No response

l0b0 avatar Feb 27 '24 21:02 l0b0

Hi, thanks for the idea :wave:

We already have nested-min-max for min() and max() -- was your proposal that we identify other standard library functions to extend this to?

jacobtylerwalls avatar Feb 28 '24 01:02 jacobtylerwalls

We already have nested-min-max for min() and max() -- was your proposal that we identify other standard library functions to extend this to?

(I wasn't aware of this checker, but) yes, things like sum, math.prod, etc. Basically anything that's idempotent and free of side effects. Of course, Python being so dynamic you can't ever be sure that nobody's overridden __add__ to do something crazy, but that's the beauty of lints being optional.

l0b0 avatar Feb 28 '24 03:02 l0b0

I also like this proposal a lot. I wonder if we should merge/rename nested-min-max in a 'chained-idempotent' (?) check or create something new entirely. We can also check that __add__ is not overidden using inference : that's the differentiating factor of pylint and why it's slow. (The same way we do it for implicit-booleaness / __bool__ without false positives for pandas/numpy objects)

Pierre-Sassoulas avatar Feb 29 '24 07:02 Pierre-Sassoulas