Skip to content

Commit 0f1245c

Browse files
cdce8pPierre-Sassoulas
authored andcommitted
Fix astroid.Inference error for undefined-variables with len()
1 parent ba4941b commit 0f1245c

File tree

4 files changed

+20
-1
lines changed

4 files changed

+20
-1
lines changed

ChangeLog

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,10 @@ Release date: TBA
4848

4949
Closes #4181
5050

51+
* Fix astroid.Inference error for undefined-variables with ``len()```
52+
53+
Closes #4215
54+
5155

5256
What's New in Pylint 2.7.2?
5357
===========================

pylint/checkers/refactoring/len_checker.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,11 @@ def visit_call(self, node):
7373
# The node is a generator or comprehension as in len([x for x in ...])
7474
self.add_message("len-as-condition", node=node)
7575
return
76-
instance = next(len_arg.infer())
76+
try:
77+
instance = next(len_arg.infer())
78+
except astroid.InferenceError:
79+
# Probably undefined-varible, abort check
80+
return
7781
mother_classes = self.base_classes_of_node(instance)
7882
affected_by_pep8 = any(
7983
t in mother_classes for t in ["str", "tuple", "list", "set"]

tests/functional/l/len_checks.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,3 +175,12 @@ def function_returning_int(r):
175175
# assert len(function_returning_generator(z))
176176
# assert len(function_returning_comprehension(z))
177177
# assert len(function_returning_function(z))
178+
179+
180+
def github_issue_4215():
181+
# Test undefined variables
182+
# https://github.com/PyCQA/pylint/issues/4215
183+
if len(undefined_var): # [undefined-variable]
184+
pass
185+
if len(undefined_var2[0]): # [undefined-variable]
186+
pass

tests/functional/l/len_checks.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,5 @@ len-as-condition:128:11:github_issue_1879:Do not use `len(SEQUENCE)` without com
2121
len-as-condition:129:11:github_issue_1879:Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty
2222
len-as-condition:130:11:github_issue_1879:Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty
2323
len-as-condition:171:11:github_issue_1879:Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty
24+
undefined-variable:183:11:github_issue_4215:Undefined variable 'undefined_var'
25+
undefined-variable:185:11:github_issue_4215:Undefined variable 'undefined_var2'

0 commit comments

Comments
 (0)