comparison_placement.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  2. # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
  3. # Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt
  4. """Checks for yoda comparisons (variable before constant)
  5. See https://en.wikipedia.org/wiki/Yoda_conditions.
  6. """
  7. from __future__ import annotations
  8. from typing import TYPE_CHECKING
  9. from astroid import nodes
  10. from pylint.checkers import BaseChecker, utils
  11. if TYPE_CHECKING:
  12. from pylint.lint import PyLinter
  13. REVERSED_COMPS = {"<": ">", "<=": ">=", ">": "<", ">=": "<="}
  14. COMPARISON_OPERATORS = frozenset(("==", "!=", "<", ">", "<=", ">="))
  15. class MisplacedComparisonConstantChecker(BaseChecker):
  16. """Checks the placement of constants in comparisons."""
  17. # configuration section name
  18. name = "comparison-placement"
  19. msgs = {
  20. "C2201": (
  21. "Comparison should be %s",
  22. "misplaced-comparison-constant",
  23. "Used when the constant is placed on the left side "
  24. "of a comparison. It is usually clearer in intent to "
  25. "place it in the right hand side of the comparison.",
  26. {"old_names": [("C0122", "old-misplaced-comparison-constant")]},
  27. )
  28. }
  29. options = ()
  30. def _check_misplaced_constant(
  31. self,
  32. node: nodes.Compare,
  33. left: nodes.NodeNG,
  34. right: nodes.NodeNG,
  35. operator: str,
  36. ) -> None:
  37. if isinstance(right, nodes.Const):
  38. return
  39. operator = REVERSED_COMPS.get(operator, operator)
  40. suggestion = f"{right.as_string()} {operator} {left.value!r}"
  41. self.add_message("misplaced-comparison-constant", node=node, args=(suggestion,))
  42. @utils.only_required_for_messages("misplaced-comparison-constant")
  43. def visit_compare(self, node: nodes.Compare) -> None:
  44. # NOTE: this checker only works with binary comparisons like 'x == 42'
  45. # but not 'x == y == 42'
  46. if len(node.ops) != 1:
  47. return
  48. left = node.left
  49. operator, right = node.ops[0]
  50. if operator in COMPARISON_OPERATORS and isinstance(left, nodes.Const):
  51. self._check_misplaced_constant(node, left, right, operator)
  52. def register(linter: PyLinter) -> None:
  53. linter.register_checker(MisplacedComparisonConstantChecker(linter))