consider_ternary_expression.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. """Check for if / assign blocks that can be rewritten with if-expressions."""
  5. from __future__ import annotations
  6. from typing import TYPE_CHECKING
  7. from astroid import nodes
  8. from pylint.checkers import BaseChecker
  9. if TYPE_CHECKING:
  10. from pylint.lint import PyLinter
  11. class ConsiderTernaryExpressionChecker(BaseChecker):
  12. name = "consider_ternary_expression"
  13. msgs = {
  14. "W0160": (
  15. "Consider rewriting as a ternary expression",
  16. "consider-ternary-expression",
  17. "Multiple assign statements spread across if/else blocks can be "
  18. "rewritten with a single assignment and ternary expression",
  19. )
  20. }
  21. def visit_if(self, node: nodes.If) -> None:
  22. if isinstance(node.parent, nodes.If):
  23. return
  24. match node:
  25. case nodes.If(body=[nodes.Assign() as bst], orelse=[nodes.Assign() as ost]):
  26. pass
  27. case _:
  28. return
  29. for bname, oname in zip(bst.targets, ost.targets):
  30. if not (
  31. isinstance(bname, nodes.AssignName)
  32. and isinstance(oname, nodes.AssignName)
  33. and bname.name == oname.name
  34. ):
  35. return
  36. self.add_message("consider-ternary-expression", node=node)
  37. def register(linter: PyLinter) -> None:
  38. linter.register_checker(ConsiderTernaryExpressionChecker(linter))