From 86b8c649061f49c7d121843675ceefe6ff3a8113 Mon Sep 17 00:00:00 2001 From: Dani Alcala <112832187+clavedeluna@users.noreply.github.com> Date: Thu, 24 Nov 2022 19:37:55 -0300 Subject: [PATCH] Fix crash when using ``enumerate`` with ``start`` and a class attribute (#7824) Co-authored-by: Pierre Sassoulas --- doc/whatsnew/fragments/7821.bugfix | 3 +++ .../refactoring/refactoring_checker.py | 16 +++++++--------- .../unnecessary_list_index_lookup.py | 19 +++++++++++++++++++ 3 files changed, 29 insertions(+), 9 deletions(-) create mode 100644 doc/whatsnew/fragments/7821.bugfix diff --git a/doc/whatsnew/fragments/7821.bugfix b/doc/whatsnew/fragments/7821.bugfix new file mode 100644 index 0000000000..af48814db7 --- /dev/null +++ b/doc/whatsnew/fragments/7821.bugfix @@ -0,0 +1,3 @@ +Fixes a crash in the ``unnecessary_list_index_lookup`` check when using ``enumerate`` with ``start`` and a class attribute. + +Closes #7821 diff --git a/pylint/checkers/refactoring/refactoring_checker.py b/pylint/checkers/refactoring/refactoring_checker.py index 87b8316092..415e204dd0 100644 --- a/pylint/checkers/refactoring/refactoring_checker.py +++ b/pylint/checkers/refactoring/refactoring_checker.py @@ -2248,15 +2248,13 @@ def _enumerate_with_start( return False, confidence def _get_start_value(self, node: nodes.NodeNG) -> tuple[int | None, Confidence]: - confidence = HIGH - - if isinstance(node, (nodes.Name, nodes.Call)): + if isinstance(node, (nodes.Name, nodes.Call, nodes.Attribute)): inferred = utils.safe_infer(node) start_val = inferred.value if inferred else None - confidence = INFERENCE - elif isinstance(node, nodes.UnaryOp): - start_val = node.operand.value - else: - start_val = node.value + return start_val, INFERENCE + if isinstance(node, nodes.UnaryOp): + return node.operand.value, HIGH + if isinstance(node, nodes.Const): + return node.value, HIGH - return start_val, confidence + return None, HIGH diff --git a/tests/functional/u/unnecessary/unnecessary_list_index_lookup.py b/tests/functional/u/unnecessary/unnecessary_list_index_lookup.py index e5cb135148..ec5ee22c20 100644 --- a/tests/functional/u/unnecessary/unnecessary_list_index_lookup.py +++ b/tests/functional/u/unnecessary/unnecessary_list_index_lookup.py @@ -130,3 +130,22 @@ def return_start(start): for i, k in enumerate(series, return_start(20)): print(series[idx]) + +for idx, val in enumerate(iterable=series, start=0): + print(series[idx]) # [unnecessary-list-index-lookup] + +result = [my_list[idx] for idx, val in enumerate(iterable=my_list)] # [unnecessary-list-index-lookup] + +for idx, val in enumerate(): + print(my_list[idx]) + +class Command: + def _get_extra_attrs(self, extra_columns): + self.extra_rows_start = 8 # pylint: disable=attribute-defined-outside-init + for index, column in enumerate(extra_columns, start=self.extra_rows_start): + pass + +Y_START = 2 +nums = list(range(20)) +for y, x in enumerate(nums, start=Y_START + 1): + pass