broad_try_clause.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. """Looks for try/except statements with too much code in the try clause."""
  5. from __future__ import annotations
  6. from typing import TYPE_CHECKING
  7. from astroid import nodes
  8. from pylint import checkers
  9. if TYPE_CHECKING:
  10. from pylint.lint import PyLinter
  11. class BroadTryClauseChecker(checkers.BaseChecker):
  12. """Checks for try clauses with too many lines.
  13. According to PEP 8, ``try`` clauses shall contain the absolute minimum
  14. amount of code. This checker enforces a maximum number of statements within
  15. ``try`` clauses.
  16. """
  17. # configuration section name
  18. name = "broad_try_clause"
  19. msgs = {
  20. "W0717": (
  21. "%s",
  22. "too-many-try-statements",
  23. "Try clause contains too many statements.",
  24. )
  25. }
  26. options = (
  27. (
  28. "max-try-statements",
  29. {
  30. "default": 1,
  31. "type": "int",
  32. "metavar": "<int>",
  33. "help": "Maximum number of statements allowed in a try clause",
  34. },
  35. ),
  36. )
  37. def _count_statements(self, try_node: nodes.TryExcept | nodes.TryFinally) -> int:
  38. statement_count = len(try_node.body)
  39. for body_node in try_node.body:
  40. if isinstance(body_node, (nodes.For, nodes.If, nodes.While, nodes.With)):
  41. statement_count += self._count_statements(body_node)
  42. return statement_count
  43. def visit_tryexcept(self, node: nodes.TryExcept | nodes.TryFinally) -> None:
  44. try_clause_statements = self._count_statements(node)
  45. if try_clause_statements > self.linter.config.max_try_statements:
  46. msg = (
  47. f"try clause contains {try_clause_statements} statements, expected at"
  48. f" most {self.linter.config.max_try_statements}"
  49. )
  50. self.add_message(
  51. "too-many-try-statements", node.lineno, node=node, args=msg
  52. )
  53. visit_tryfinally = visit_tryexcept
  54. def register(linter: PyLinter) -> None:
  55. linter.register_checker(BroadTryClauseChecker(linter))