comparison_placement.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. """
  4. Checks for yoda comparisons (variable before constant)
  5. See https://en.wikipedia.org/wiki/Yoda_conditions
  6. """
  7. from astroid import nodes
  8. from pylint.checkers import BaseChecker, utils
  9. from pylint.interfaces import IAstroidChecker
  10. REVERSED_COMPS = {"<": ">", "<=": ">=", ">": "<", ">=": "<="}
  11. COMPARISON_OPERATORS = frozenset(("==", "!=", "<", ">", "<=", ">="))
  12. class MisplacedComparisonConstantChecker(BaseChecker):
  13. """Checks the placement of constants in comparisons"""
  14. __implements__ = (IAstroidChecker,)
  15. # configuration section name
  16. name = "comparison-placement"
  17. msgs = {
  18. "C2201": (
  19. "Comparison should be %s",
  20. "misplaced-comparison-constant",
  21. "Used when the constant is placed on the left side "
  22. "of a comparison. It is usually clearer in intent to "
  23. "place it in the right hand side of the comparison.",
  24. {"old_names": [("C0122", "old-misplaced-comparison-constant")]},
  25. )
  26. }
  27. options = ()
  28. def _check_misplaced_constant(
  29. self,
  30. node: nodes.Compare,
  31. left: nodes.NodeNG,
  32. right: nodes.NodeNG,
  33. operator: str,
  34. ):
  35. if isinstance(right, nodes.Const):
  36. return
  37. operator = REVERSED_COMPS.get(operator, operator)
  38. suggestion = f"{right.as_string()} {operator} {left.value!r}"
  39. self.add_message("misplaced-comparison-constant", node=node, args=(suggestion,))
  40. @utils.check_messages("misplaced-comparison-constant")
  41. def visit_compare(self, node: nodes.Compare) -> None:
  42. # NOTE: this checker only works with binary comparisons like 'x == 42'
  43. # but not 'x == y == 42'
  44. if len(node.ops) != 1:
  45. return
  46. left = node.left
  47. operator, right = node.ops[0]
  48. if operator in COMPARISON_OPERATORS and isinstance(left, nodes.Const):
  49. self._check_misplaced_constant(node, left, right, operator)
  50. def register(linter):
  51. """Required method to auto register this checker."""
  52. linter.register_checker(MisplacedComparisonConstantChecker(linter))