set_membership.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from astroid import nodes
  2. from pylint.checkers import BaseChecker
  3. from pylint.checkers.utils import check_messages
  4. from pylint.interfaces import IAstroidChecker
  5. from pylint.lint import PyLinter
  6. class SetMembershipChecker(BaseChecker):
  7. __implements__ = (IAstroidChecker,)
  8. name = "set_membership"
  9. priority = -1
  10. msgs = {
  11. "R6201": (
  12. "Consider using set for membership test",
  13. "use-set-for-membership",
  14. "Membership tests are more efficient when performed on "
  15. "a lookup optimized datatype like ``sets``.",
  16. ),
  17. }
  18. def __init__(self, linter: PyLinter) -> None:
  19. """Initialize checker instance."""
  20. super().__init__(linter=linter)
  21. @check_messages("use-set-for-membership")
  22. def visit_compare(self, node: nodes.Compare) -> None:
  23. for op, comparator in node.ops:
  24. if op == "in":
  25. self._check_in_comparison(comparator)
  26. def _check_in_comparison(self, comparator: nodes.NodeNG) -> None:
  27. """Checks for membership comparisons with in-place container objects."""
  28. if not isinstance(comparator, nodes.BaseContainer) or isinstance(
  29. comparator, nodes.Set
  30. ):
  31. return
  32. # Heuristic - We need to be sure all items in set are hashable
  33. if all(isinstance(item, nodes.Const) for item in comparator.elts):
  34. self.add_message("use-set-for-membership", node=comparator)
  35. def register(linter: PyLinter) -> None:
  36. linter.register_checker(SetMembershipChecker(linter))