Consider extending PLR2004
to cover iterables with magic values
#12155
Labels
rule
Implementing or modifying a lint rule
PLR2004
to cover iterables with magic values
#12155
Keywords:
PLR2004
,magic-value-comparison
Here's a suggestion regarding
PLR2004
, although I don't quite understand the final optimal form it should take (I've found a comment that Ruff tries to be a "faithful implementation of the Pylint rule" in this case, so I do not insist on changing the behavior of the original rule).Imagine that a developer wants to check if the
status_code
of some request is in a redirect group (e.g.,301
,302
).A naive approach is to simply check for equality:
The developer immediately receives 3 errors:
PLR1714
(repeated-equality-comparison
) and 2 instances ofPLR2004
.More advanced Python developers will skip the step above and just write:
And all 3 errors will disappear, even though the problem with magic value comparison still remains.
The code above is also the default suggestion from
PLR1714
, and copy-pasting the solution (which mysteriously removed 2 more warnings) can be misleading for inexperienced developers.As I mentioned above, I'm not sure how to properly address this issue and I'm obviously unaware of some implementational pitfalls, but I believe that forcing this check even for homogeneous iterables (such as
list[int]
ortuple[int]
) would be a pretty good step in the right direction.Hoping to get some feedback! :)
The text was updated successfully, but these errors were encountered: