From 6b65cef733a9154fc0a48d77121330a4ec1ed104 Mon Sep 17 00:00:00 2001 From: Pang Yu Shao Date: Sun, 9 May 2021 23:12:24 +0800 Subject: [PATCH] Added additional logic and tests for (#3389) --- .../refactoring/recommendation_checker.py | 7 +++++++ .../c/consider/consider_using_dict_items.py | 15 ++++++++++++++- .../c/consider/consider_using_dict_items.txt | 1 + 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/pylint/checkers/refactoring/recommendation_checker.py b/pylint/checkers/refactoring/recommendation_checker.py index 0bcd2cbf153..5ea13616b96 100644 --- a/pylint/checkers/refactoring/recommendation_checker.py +++ b/pylint/checkers/refactoring/recommendation_checker.py @@ -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 diff --git a/tests/functional/c/consider/consider_using_dict_items.py b/tests/functional/c/consider/consider_using_dict_items.py index 9b067728341..233fa98d8a9 100644 --- a/tests/functional/c/consider/consider_using_dict_items.py +++ b/tests/functional/c/consider/consider_using_dict_items.py @@ -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} @@ -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]) diff --git a/tests/functional/c/consider/consider_using_dict_items.txt b/tests/functional/c/consider/consider_using_dict_items.txt index 46662e5ce93..a86b74e9788 100644 --- a/tests/functional/c/consider/consider_using_dict_items.txt +++ b/tests/functional/c/consider/consider_using_dict_items.txt @@ -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()