Skip to content

Commit

Permalink
len-as-condition: fix false positives when len() wasn't used in logic…
Browse files Browse the repository at this point in the history
…al test (#1332)

Closes #1325 and #1331
  • Loading branch information
rogalski committed Feb 21, 2017
1 parent d274655 commit ea964a0
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
8 changes: 5 additions & 3 deletions pylint/checkers/refactoring.py
Original file line number Diff line number Diff line change
Expand Up @@ -653,9 653,11 @@ def visit_call(self, node):

# we're finally out of any nested boolean operations so check if
# this len() call is part of a test condition
if _node_is_test_condition(parent):
self.add_message('len-as-condition', node=node)

if not _node_is_test_condition(parent):
return
if not (node is parent.test or parent.test.parent_of(node)):
return
self.add_message('len-as-condition', node=node)

@utils.check_messages('len-as-condition')
def visit_unaryop(self, node):
Expand Down
18 changes: 18 additions & 0 deletions pylint/test/functional/len_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 45,21 @@

def some_func():
return len('TEST') > 0 # Should be fine


def github_issue_1325():
l = [1, 2, 3]
length = len(l) if l else 0
return length


def github_issue_1331(*args):
assert False, len(args)


def github_issue_1331_v2(*args):
assert len(args), args # [len-as-condition]


def github_issue_1331_v3(*args):
assert len(args) or z, args # [len-as-condition]
2 changes: 2 additions & 0 deletions pylint/test/functional/len_checks.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 8,5 @@ len-as-condition:20::Do not use `len(SEQUENCE)` as condition value
len-as-condition:26::Do not use `len(SEQUENCE)` as condition value
len-as-condition:30::Do not use `len(SEQUENCE)` as condition value
len-as-condition:43::Do not use `len(SEQUENCE)` as condition value
len-as-condition:61:github_issue_1331_v2:Do not use `len(SEQUENCE)` as condition value
len-as-condition:65:github_issue_1331_v3:Do not use `len(SEQUENCE)` as condition value

0 comments on commit ea964a0

Please sign in to comment.