Skip to content

Commit

Permalink
undefined-variable can now find undefined loop iterables
Browse files Browse the repository at this point in the history
Close #498
  • Loading branch information
PCManticore committed Dec 16, 2019
1 parent e63e664 commit 58b9e64
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 1 deletion.
4 changes: 4 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ Release date: TBA

Close #3301

* ``undefined-variable`` can now find undefined loop iterables

Close #498

* ``safe_infer`` can infer a value as long as all the paths share the same type.

Close #2503
Expand Down
10 changes: 9 additions & 1 deletion pylint/checkers/variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -546,7 +546,7 @@ def mark_as_consumed(self, name, new_node):
del self.to_consume[name]

def get_next_to_consume(self, node):
# mark the name as consumed if it's defined in this scope
# Get the definition of `node` from this scope
name = node.name
parent_node = node.parent
found_node = self.to_consume.get(name)
Expand All @@ -558,6 +558,14 @@ def get_next_to_consume(self, node):
lhs = found_node[0].parent.targets[0]
if lhs.name == name: # this name is defined in this very statement
found_node = None

if (
found_node
and isinstance(parent_node, astroid.For)
and parent_node.iter == node
and parent_node.target in found_node
):
found_node = None
return found_node


Expand Down
7 changes: 7 additions & 0 deletions tests/functional/u/undefined_variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,3 +274,10 @@ def func_should_fail(_dt: datetime): # [used-before-assignment]
def tick(counter: Counter, name: str, dictionary: OrderedDict) -> OrderedDict:
counter[name] += 1
return dictionary


# pylint: disable=unused-argument
def not_using_loop_variable_accordingly(iterator):
for iteree in iteree: # [undefined-variable]
yield iteree
# pylint: enable=unused-argument
1 change: 1 addition & 0 deletions tests/functional/u/undefined_variable.txt
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,4 @@ undefined-variable:170::Undefined variable 'unicode_3'
undefined-variable:225:LambdaClass4.<lambda>:Undefined variable 'LambdaClass4'
undefined-variable:233:LambdaClass5.<lambda>:Undefined variable 'LambdaClass5'
used-before-assignment:254:func_should_fail:Using variable 'datetime' before assignment
undefined-variable:281:not_using_loop_variable_accordingly:Undefined variable 'iteree'

0 comments on commit 58b9e64

Please sign in to comment.