Skip to content

Commit

Permalink
[compare-to-zero] More actionnable and understandable message
Browse files Browse the repository at this point in the history
Originally done in order to normalize the use-implicit-booleaness check.
This make the message more understandable and permit to make #6870 more
reviewable.
  • Loading branch information
Pierre-Sassoulas committed Nov 6, 2022
1 parent f5f9e26 commit 6d896f3
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
17 changes: 15 additions & 2 deletions pylint/extensions/comparetozero.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class CompareToZeroChecker(checkers.BaseChecker):
name = "compare-to-zero"
msgs = {
"C2001": (
"Avoid comparisons to zero",
'"%s" can be simplified to "%s" as 0 is falsey',
"compare-to-zero",
"Used when Pylint detects comparison to a 0 constant.",
)
Expand Down Expand Up @@ -66,12 +66,25 @@ def visit_compare(self, node: nodes.Compare) -> None:
# 0 ?? X
if _is_constant_zero(op_1) and op_2 in _operators:
error_detected = True
op = op_3
# X ?? 0
elif op_2 in _operators and _is_constant_zero(op_3):
error_detected = True
op = op_1

if error_detected:
self.add_message("compare-to-zero", node=node, confidence=HIGH)
original = f"{op_1.as_string()} {op_2} {op_3.as_string()}"
suggestion = (
op.as_string()
if op_2 in {"!=", "is not"}
else f"not {op.as_string()}"
)
self.add_message(
"compare-to-zero",
args=(original, suggestion),
node=node,
confidence=HIGH,
)


def register(linter: PyLinter) -> None:
Expand Down
8 changes: 4 additions & 4 deletions tests/functional/ext/comparetozero/comparetozero.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
compare-to-zero:6:3:6:9::Avoid comparisons to zero:HIGH
compare-to-zero:9:3:9:13::Avoid comparisons to zero:HIGH
compare-to-zero:12:3:12:9::Avoid comparisons to zero:HIGH
compare-to-zero:15:3:15:9::Avoid comparisons to zero:HIGH
compare-to-zero:6:3:6:9::"""X is 0"" can be simplified to ""not X"" as 0 is falsey":HIGH
compare-to-zero:9:3:9:13::"""Y is not 0"" can be simplified to ""Y"" as 0 is falsey":HIGH
compare-to-zero:12:3:12:9::"""X == 0"" can be simplified to ""not X"" as 0 is falsey":HIGH
compare-to-zero:15:3:15:9::"""Y != 0"" can be simplified to ""Y"" as 0 is falsey":HIGH

0 comments on commit 6d896f3

Please sign in to comment.