comparetozero.py 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  2. # For details: https://github.com/pylint-dev/pylint/blob/main/LICENSE
  3. # Copyright (c) https://github.com/pylint-dev/pylint/blob/main/CONTRIBUTORS.txt
  4. """Looks for comparisons to zero."""
  5. from __future__ import annotations
  6. import itertools
  7. from typing import TYPE_CHECKING
  8. import astroid
  9. from astroid import nodes
  10. from pylint import checkers
  11. from pylint.checkers import utils
  12. from pylint.interfaces import HIGH
  13. if TYPE_CHECKING:
  14. from pylint.lint import PyLinter
  15. def _is_constant_zero(node: str | nodes.NodeNG) -> bool:
  16. # We have to check that node.value is not False because node.value == 0 is True
  17. # when node.value is False
  18. return (
  19. isinstance(node, astroid.Const) and node.value == 0 and node.value is not False
  20. )
  21. class CompareToZeroChecker(checkers.BaseChecker):
  22. """Checks for comparisons to zero.
  23. Most of the time you should use the fact that integers with a value of 0 are false.
  24. An exception to this rule is when 0 is allowed in the program and has a
  25. different meaning than None!
  26. """
  27. # configuration section name
  28. name = "compare-to-zero"
  29. msgs = {
  30. "C2001": (
  31. '"%s" can be simplified to "%s" as 0 is falsey',
  32. "compare-to-zero",
  33. "Used when Pylint detects comparison to a 0 constant.",
  34. )
  35. }
  36. options = ()
  37. @utils.only_required_for_messages("compare-to-zero")
  38. def visit_compare(self, node: nodes.Compare) -> None:
  39. # pylint: disable=duplicate-code
  40. _operators = ["!=", "==", "is not", "is"]
  41. # note: astroid.Compare has the left most operand in node.left
  42. # while the rest are a list of tuples in node.ops
  43. # the format of the tuple is ('compare operator sign', node)
  44. # here we squash everything into `ops` to make it easier for processing later
  45. ops: list[tuple[str, nodes.NodeNG]] = [("", node.left)]
  46. ops.extend(node.ops)
  47. iter_ops = iter(ops)
  48. all_ops = list(itertools.chain(*iter_ops))
  49. for ops_idx in range(len(all_ops) - 2):
  50. op_1 = all_ops[ops_idx]
  51. op_2 = all_ops[ops_idx + 1]
  52. op_3 = all_ops[ops_idx + 2]
  53. error_detected = False
  54. # 0 ?? X
  55. if _is_constant_zero(op_1) and op_2 in _operators:
  56. error_detected = True
  57. op = op_3
  58. # X ?? 0
  59. elif op_2 in _operators and _is_constant_zero(op_3):
  60. error_detected = True
  61. op = op_1
  62. if error_detected:
  63. original = f"{op_1.as_string()} {op_2} {op_3.as_string()}"
  64. suggestion = (
  65. op.as_string()
  66. if op_2 in {"!=", "is not"}
  67. else f"not {op.as_string()}"
  68. )
  69. self.add_message(
  70. "compare-to-zero",
  71. args=(original, suggestion),
  72. node=node,
  73. confidence=HIGH,
  74. )
  75. def register(linter: PyLinter) -> None:
  76. linter.register_checker(CompareToZeroChecker(linter))