ellipsis_checker.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. """Ellipsis checker for Python code."""
  5. from __future__ import annotations
  6. from typing import TYPE_CHECKING
  7. from astroid import nodes
  8. from pylint.checkers import BaseChecker
  9. from pylint.checkers.utils import only_required_for_messages
  10. if TYPE_CHECKING:
  11. from pylint.lint import PyLinter
  12. class EllipsisChecker(BaseChecker):
  13. name = "unnecessary_ellipsis"
  14. msgs = {
  15. "W2301": (
  16. "Unnecessary ellipsis constant",
  17. "unnecessary-ellipsis",
  18. "Used when the ellipsis constant is encountered and can be avoided. "
  19. "A line of code consisting of an ellipsis is unnecessary if "
  20. "there is a docstring on the preceding line or if there is a "
  21. "statement in the same scope.",
  22. )
  23. }
  24. @only_required_for_messages("unnecessary-ellipsis")
  25. def visit_const(self, node: nodes.Const) -> None:
  26. """Check if the ellipsis constant is used unnecessarily.
  27. Emits a warning when:
  28. - A line consisting of an ellipsis is preceded by a docstring.
  29. - A statement exists in the same scope as the ellipsis.
  30. For example: A function consisting of an ellipsis followed by a
  31. return statement on the next line.
  32. """
  33. if (
  34. node.pytype() == "builtins.Ellipsis"
  35. and isinstance(node.parent, nodes.Expr)
  36. and (
  37. (
  38. isinstance(node.parent.parent, (nodes.ClassDef, nodes.FunctionDef))
  39. and node.parent.parent.doc_node
  40. )
  41. or len(node.parent.parent.body) > 1
  42. )
  43. ):
  44. self.add_message("unnecessary-ellipsis", node=node)
  45. def register(linter: PyLinter) -> None:
  46. linter.register_checker(EllipsisChecker(linter))