Skip to content

Commit

Permalink
Added additional logic and tests for (pylint-dev#3389)
Browse files Browse the repository at this point in the history
  • Loading branch information
yushao2 committed May 9, 2021
1 parent b38c035 commit 6b65cef
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
7 changes: 7 additions & 0 deletions pylint/checkers/refactoring/recommendation_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,13 @@ def _check_consider_using_dict_items(self, node):
continue
if iterating_object_name != subscript.value.name:
continue
last_definition_lineno = value.lookup(value.name)[1][-1].lineno
if last_definition_lineno > node.lineno:
# Ignore this subscript if it has been redefined after
# the for loop. This checks for the line number using .lookup()
# to get the line number where the iterating object was last
# defined and compare that to the for loop's line number
continue
if subscript.value.scope() != node.scope():
# Ignore this subscript if it's not in the same
# scope. This means that in the body of the for
Expand Down
15 changes: 14 additions & 1 deletion tests/functional/c/consider/consider_using_dict_items.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Emit a message for iteration through dict keys and subscripting dict with key."""

# pylint: disable=missing-docstring, import-error, useless-object-inheritance, unsubscriptable-object, too-few-public-methods
# pylint: disable=missing-docstring, unsubscriptable-object

def bad():
a_dict = {1:1, 2:2, 3:3}
Expand All @@ -15,3 +15,16 @@ def good():
a_dict = {1:1, 2:2, 3:3}
for k in a_dict:
print(k)

out_of_scope_dict = dict()

def another_bad():
for k in out_of_scope_dict:# [consider-using-dict-items]
print(out_of_scope_dict[k])

def another_good():
for k in out_of_scope_dict:
k = 1
k = 2
k = 3
print(out_of_scope_dict[k])
1 change: 1 addition & 0 deletions tests/functional/c/consider/consider_using_dict_items.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
consider-using-dict-items:7:4:bad:Consider iterating with .items()
consider-using-dict-items:10:4:bad:Consider iterating with .items()
consider-using-dict-items:22:4:another_bad:Consider iterating with .items()

0 comments on commit 6b65cef

Please sign in to comment.