consider_ternary_expression.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. if len(node.body) != 1 or len(node.orelse) != 1:
  25. return
  26. bst = node.body[0]
  27. ost = node.orelse[0]
  28. if not isinstance(bst, nodes.Assign) or not isinstance(ost, nodes.Assign):
  29. return
  30. for bname, oname in zip(bst.targets, ost.targets):
  31. if not isinstance(bname, nodes.AssignName) or not isinstance(
  32. oname, nodes.AssignName
  33. ):
  34. return
  35. if bname.name != oname.name:
  36. return
  37. self.add_message("consider-ternary-expression", node=node)
  38. def register(linter: PyLinter) -> None:
  39. linter.register_checker(ConsiderTernaryExpressionChecker(linter))