Skip to content

Commit e44486a

Browse files
committed
No longer flag constant list, tuple and dict
1 parent 022a26e commit e44486a

File tree

3 files changed

+51
-12
lines changed

3 files changed

+51
-12
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
* Renamed the global usage in loop to `loop-global-usage`
66
* Added support for invariant f-strings
7+
* Bugfix: Doesn't highlight list, tuple or dict with only constant values as being invariant
78

89
## 0.7.1 (1st April 2022)
910

perflint/for_loop_checker.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,27 @@ def visit_while(self, node: nodes.While) -> None:
193193
self._loop_assignments.append(set())
194194
self._ignore.append(node.test)
195195

196+
def _visit_sequence(self, node: Union[nodes.List, nodes.Tuple]) -> None:
197+
if not node.elts:
198+
self._ignore.append(node)
199+
elif all(isinstance(e, nodes.Const) for e in node.elts):
200+
self._ignore.append(node)
201+
202+
def visit_list(self, node: nodes.List) -> None:
203+
self._visit_sequence(node)
204+
205+
def visit_tuple(self, node: nodes.Tuple) -> None:
206+
self._visit_sequence(node)
207+
208+
def visit_dict(self, node: nodes.Dict) -> None:
209+
if not node.items:
210+
self._ignore.append(node)
211+
elif all(
212+
isinstance(k, nodes.Const) and isinstance(v, nodes.Const)
213+
for k, v in node.items
214+
):
215+
self._ignore.append(node)
216+
196217
@checker_utils.check_messages("loop-invariant-statement")
197218
def leave_for(self, node: nodes.For) -> None:
198219
self._leave_loop(node)

tests/test_loop_invariant.py

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -279,15 +279,32 @@ def test(): #@
279279
with self.assertNoMessages():
280280
self.walk(test_func)
281281

282-
# TODO : Fix constant checks
283-
# def test_constants(self):
284-
# test_func = astroid.extract_node(
285-
# """
286-
# def test(): #@
287-
# for _ in fruits:
288-
# fruits = ["apple", "banana", "pear"]
289-
# """
290-
# )
291-
292-
# with self.assertNoMessages():
293-
# self.walk(test_func)
282+
def test_constants(self):
283+
test_func = astroid.extract_node(
284+
"""
285+
def test(): #@
286+
for _ in fruits:
287+
fruits = ["apple", "banana", "pear"]
288+
fruits_tuple = ("apple", "banana", "pear")
289+
_ = []
290+
_ = [1, 2, 3]
291+
_ = ()
292+
_ = (1, 2, 3)
293+
"""
294+
)
295+
296+
with self.assertNoMessages():
297+
self.walk(test_func)
298+
299+
def test_constant_dictionaries(self):
300+
test_func = astroid.extract_node(
301+
"""
302+
def test(): #@
303+
for _ in fruits:
304+
_ = {}
305+
fruits = {0: 1, 1: 2}
306+
"""
307+
)
308+
309+
with self.assertNoMessages():
310+
self.walk(test_func)

0 commit comments

Comments
 (0)