not_checker.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. import astroid
  4. from astroid import nodes
  5. from pylint import checkers, interfaces
  6. from pylint.checkers import utils
  7. class NotChecker(checkers.BaseChecker):
  8. """checks for too many not in comparison expressions
  9. - "not not" should trigger a warning
  10. - "not" followed by a comparison should trigger a warning
  11. """
  12. __implements__ = (interfaces.IAstroidChecker,)
  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.check_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()
  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. )