Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

check_elif.py 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # Copyright (c) 2015 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
  2. # Copyright (c) 2016-2017 Claudiu Popa <pcmanticore@gmail.com>
  3. # Copyright (c) 2016 Glenn Matthews <glmatthe@cisco.com>
  4. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  5. # For details: https://github.com/PyCQA/pylint/blob/master/COPYING
  6. import astroid
  7. from pylint.checkers import BaseTokenChecker
  8. from pylint.checkers.utils import check_messages
  9. from pylint.interfaces import ITokenChecker, IAstroidChecker
  10. class ElseifUsedChecker(BaseTokenChecker):
  11. """Checks for use of "else if" when a "elif" could be used
  12. """
  13. __implements__ = (ITokenChecker, IAstroidChecker)
  14. name = 'else_if_used'
  15. msgs = {'R5501': ('Consider using "elif" instead of "else if"',
  16. 'else-if-used',
  17. 'Used when an else statement is immediately followed by '
  18. 'an if statement and does not contain statements that '
  19. 'would be unrelated to it.'),
  20. }
  21. def __init__(self, linter=None):
  22. BaseTokenChecker.__init__(self, linter)
  23. self._init()
  24. def _init(self):
  25. self._elifs = []
  26. self._if_counter = 0
  27. def process_tokens(self, tokens):
  28. # Process tokens and look for 'if' or 'elif'
  29. for _, token, _, _, _ in tokens:
  30. if token == 'elif':
  31. self._elifs.append(True)
  32. elif token == 'if':
  33. self._elifs.append(False)
  34. def leave_module(self, _):
  35. self._init()
  36. def visit_ifexp(self, _):
  37. self._if_counter += 1
  38. def visit_comprehension(self, node):
  39. self._if_counter += len(node.ifs)
  40. @check_messages('else-if-used')
  41. def visit_if(self, node):
  42. if isinstance(node.parent, astroid.If):
  43. orelse = node.parent.orelse
  44. # current if node must directly follow a "else"
  45. if orelse and orelse == [node]:
  46. if not self._elifs[self._if_counter]:
  47. self.add_message('else-if-used', node=node)
  48. self._if_counter += 1
  49. def register(linter):
  50. """Required method to auto register this checker.
  51. :param linter: Main interface object for Pylint plugins
  52. :type linter: Pylint object
  53. """
  54. linter.register_checker(ElseifUsedChecker(linter))