From 6abd0a03e2ac33c1f96ccdcf06d874ece4c83074 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 +++ .../checkers/refactoring/refactoring_checker.py | 16 +++++++--------- .../unnecessary/unnecessary_list_index_lookup.py | 11 +++++++++++ 3 files changed, 21 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 9cc316649f..6a79ce55a7 100644 --- a/pylint/checkers/refactoring/refactoring_checker.py +++ b/pylint/checkers/refactoring/refactoring_checker.py @@ -2306,15 +2306,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 eb23938bcb..ec5ee22c20 100644 --- a/tests/functional/u/unnecessary/unnecessary_list_index_lookup.py +++ b/tests/functional/u/unnecessary/unnecessary_list_index_lookup.py @@ -138,3 +138,14 @@ def return_start(start): 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