pylint
pylint copied to clipboard
Suggest flattening nested idempotent function applications
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 tomin(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 orfirst = min(a, b, c, d)
if
second
is not used later.
Additional context
No response
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?
We already have
nested-min-max
formin()
andmax()
-- 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.
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)