diff options
Diffstat (limited to 'pylint/checkers/base.py')
-rw-r--r-- | pylint/checkers/base.py | 28 |
1 files changed, 26 insertions, 2 deletions
diff --git a/pylint/checkers/base.py b/pylint/checkers/base.py index 927e77b..2e5613a 100644 --- a/pylint/checkers/base.py +++ b/pylint/checkers/base.py @@ -1443,11 +1443,20 @@ class LambdaForComprehensionChecker(_BasicChecker): self.add_message('deprecated-lambda', node=node) class ComparisonChecker(_BasicChecker): - """checks for 'expr == True', 'expr == False' and 'expr == None'""" + """checks for singleton comparison and for yoda condition + + - singleton comparison: 'expr == True', 'expr == False' and 'expr == None' + - yoda condition: 'const "comp" var' where comp can be '==', '!=', '<', + '<=', '>' or '>=' + """ msgs = {'C0121': ('Comparison to %s should be %s', 'singleton-comparison', 'Used when an expression is compared to singleton ' 'values like True, False or None.'), + 'W0151': ('Comparison should be %s', + 'misplaced-comparison-constant', + 'Used when the constant is placed on the left side' + 'of a comparison'), } def check_singleton_comparison(self, singleton, root_node): @@ -1466,7 +1475,18 @@ class ComparisonChecker(_BasicChecker): node=root_node, args=(None, "'expr is None'")) - @check_messages('singleton-comparison') + def _warn_misplaced_constant(self, node, left, right, operator): + if isinstance(right, astroid.Name): + reverse_op = {'<': '>', '<=': '>=', '>': '<', '>=': '<='} + if operator in reverse_op: + operator = reverse_op[operator] + suggestion = '%s %s %s' % (right.name, operator, left.value) + else: + suggestion = 'between a variable and a constant' + self.add_message('misplaced-comparison-constant', node=node, + args=(suggestion,)) + + @check_messages('singleton-comparison', 'misplaced-comparison-constant') def visit_compare(self, node): # NOTE: this checker only works with binary comparisons like 'x == 42' # but not 'x == y == 42' @@ -1477,9 +1497,13 @@ class ComparisonChecker(_BasicChecker): operator, right = node.ops[0] if operator == '==': if isinstance(left, astroid.Const): + self._warn_misplaced_constant(node, left, right, operator) self.check_singleton_comparison(left, node) elif isinstance(right, astroid.Const): self.check_singleton_comparison(right, node) + elif (operator in ('<', '<=', '>', '>=', '!=') + and isinstance(left, astroid.Const)): + self._warn_misplaced_constant(node, left, right, operator) def register(linter): |