check_elif.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # Copyright (c) 2015 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
  2. # Copyright (c) 2016-2020 Claudiu Popa <pcmanticore@gmail.com>
  3. # Copyright (c) 2016 Glenn Matthews <glmatthe@cisco.com>
  4. # Copyright (c) 2018 Ville Skyttä <ville.skytta@iki.fi>
  5. # Copyright (c) 2019-2021 Pierre Sassoulas <pierre.sassoulas@gmail.com>
  6. # Copyright (c) 2020 hippo91 <guillaume.peillex@gmail.com>
  7. # Copyright (c) 2020 Anthony Sottile <asottile@umich.edu>
  8. # Copyright (c) 2021 bot <bot@noreply.github.com>
  9. # Copyright (c) 2021 Daniël van Noord <13665637+DanielNoord@users.noreply.github.com>
  10. # Copyright (c) 2021 Marc Mueller <30130371+cdce8p@users.noreply.github.com>
  11. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  12. # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
  13. from astroid import nodes
  14. from pylint.checkers import BaseTokenChecker
  15. from pylint.checkers.utils import check_messages
  16. from pylint.interfaces import HIGH, IAstroidChecker, ITokenChecker
  17. class ElseifUsedChecker(BaseTokenChecker):
  18. """Checks for use of "else if" when an "elif" could be used"""
  19. __implements__ = (ITokenChecker, IAstroidChecker)
  20. name = "else_if_used"
  21. msgs = {
  22. "R5501": (
  23. 'Consider using "elif" instead of "else if"',
  24. "else-if-used",
  25. "Used when an else statement is immediately followed by "
  26. "an if statement and does not contain statements that "
  27. "would be unrelated to it.",
  28. )
  29. }
  30. def __init__(self, linter=None):
  31. super().__init__(linter)
  32. self._init()
  33. def _init(self):
  34. self._elifs = {}
  35. def process_tokens(self, tokens):
  36. """Process tokens and look for 'if' or 'elif'"""
  37. self._elifs = {
  38. begin: token for _, token, begin, _, _ in tokens if token in {"elif", "if"}
  39. }
  40. def leave_module(self, _: nodes.Module) -> None:
  41. self._init()
  42. @check_messages("else-if-used")
  43. def visit_if(self, node: nodes.If) -> None:
  44. """Current if node must directly follow an 'else'"""
  45. if (
  46. isinstance(node.parent, nodes.If)
  47. and node.parent.orelse == [node]
  48. and (node.lineno, node.col_offset) in self._elifs
  49. and self._elifs[(node.lineno, node.col_offset)] == "if"
  50. ):
  51. self.add_message("else-if-used", node=node, confidence=HIGH)
  52. def register(linter):
  53. """Required method to auto register this checker.
  54. :param linter: Main interface object for Pylint plugins
  55. :type linter: Pylint object
  56. """
  57. linter.register_checker(ElseifUsedChecker(linter))