1 from logilab
import astng
3 from pylint
.interfaces
import IASTNGChecker
4 from pylint
.checkers
import BaseChecker
6 class MissingElseChecker(BaseChecker
):
8 Checks for if blocks that don't have an else clause
11 __implements__
= IASTNGChecker
15 'W9901': ('if with no else clause',
16 "There's an if block (with no elif) with no else clause"),
17 'W9902': ('if/elif with no else clause',
18 "There's an if/elif set of blocks with no corresponding else clause"),
22 {'default': False, 'type': 'yn', 'metavar': '<y_or_n>',
23 'help': 'Warn about missing else clause when there is an if (but no elif)'}
25 ('warn_if_elif_no_else',
26 {'default': True, 'type': 'yn', 'metavar': '<y_or_n>',
27 'help': 'Warn about if/elif blocks that have no corresponding else clause'}
31 # this is important so that your checker is executed before others
34 def visit_if(self
, node
):
35 assert len(node
.getChildren()) % 2 == 1, "There are an even amount of nodes for "+repr(node
)
37 # True if there is an else clause on this if block
38 has_else
= node
.getChildren()[-1] is not None
40 # True if there are elif methods
41 has_elifs
= len(node
.getChildren()) > 3
43 if self
.config
.warn_if_no_else
and not has_else
:
44 self
.add_message('W9901', line
=node
.lineno
)
46 if self
.config
.warn_if_elif_no_else
and has_elifs
and not has_else
:
47 self
.add_message('W9902', line
=node
.lineno
)
52 """required method to auto register this checker"""
53 linter
.register_checker(MissingElseChecker(linter
))