not_checker.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. import astroid
  5. from astroid import nodes
  6. from pylint import checkers
  7. from pylint.checkers import utils
  8. class NotChecker(checkers.BaseChecker):
  9. """Checks for too many not in comparison expressions.
  10. - "not not" should trigger a warning
  11. - "not" followed by a comparison should trigger a warning
  12. """
  13. msgs = {
  14. "C0113": (
  15. 'Consider changing "%s" to "%s"',
  16. "unneeded-not",
  17. "Used when a boolean expression contains an unneeded negation.",
  18. )
  19. }
  20. name = "refactoring"
  21. reverse_op = {
  22. "<": ">=",
  23. "<=": ">",
  24. ">": "<=",
  25. ">=": "<",
  26. "==": "!=",
  27. "!=": "==",
  28. "in": "not in",
  29. "is": "is not",
  30. }
  31. # sets are not ordered, so for example "not set(LEFT_VALS) <= set(RIGHT_VALS)" is
  32. # not equivalent to "set(LEFT_VALS) > set(RIGHT_VALS)"
  33. skipped_nodes = (nodes.Set,)
  34. # 'builtins' py3, '__builtin__' py2
  35. skipped_classnames = [f"builtins.{qname}" for qname in ("set", "frozenset")]
  36. @utils.only_required_for_messages("unneeded-not")
  37. def visit_unaryop(self, node: nodes.UnaryOp) -> None:
  38. if node.op != "not":
  39. return
  40. operand = node.operand
  41. if isinstance(operand, nodes.UnaryOp) and operand.op == "not":
  42. self.add_message(
  43. "unneeded-not",
  44. node=node,
  45. args=(node.as_string(), operand.operand.as_string()),
  46. )
  47. elif isinstance(operand, nodes.Compare):
  48. left = operand.left
  49. # ignore multiple comparisons
  50. if len(operand.ops) > 1:
  51. return
  52. operator, right = operand.ops[0]
  53. if operator not in self.reverse_op:
  54. return
  55. # Ignore __ne__ as function of __eq__
  56. frame = node.frame(future=True)
  57. if frame.name == "__ne__" and operator == "==":
  58. return
  59. for _type in (utils.node_type(left), utils.node_type(right)):
  60. if not _type:
  61. return
  62. if isinstance(_type, self.skipped_nodes):
  63. return
  64. if (
  65. isinstance(_type, astroid.Instance)
  66. and _type.qname() in self.skipped_classnames
  67. ):
  68. return
  69. suggestion = (
  70. f"{left.as_string()} {self.reverse_op[operator]} {right.as_string()}"
  71. )
  72. self.add_message(
  73. "unneeded-not", node=node, args=(node.as_string(), suggestion)
  74. )