Skip to content

Commit

Permalink
Fix uncaught ValueError in infer_getitem with zero-step slices (#1844)
Browse files Browse the repository at this point in the history
Fixes #1843
  • Loading branch information
nelfin committed Nov 13, 2022
1 parent 04fad05 commit 50a7cd8
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 0 deletions.
3 changes: 3 additions & 0 deletions ChangeLog
Expand Up @@ -38,6 +38,9 @@ Release date: TBA

Refs PyCQA/pylint#7706

* Catch ``ValueError`` when indexing some builtin containers and sequences during inference.

Closes #1843

What's New in astroid 2.12.12?
==============================
Expand Down
2 changes: 2 additions & 0 deletions astroid/inference.py
Expand Up @@ -27,6 +27,7 @@
AstroidError,
AstroidIndexError,
AstroidTypeError,
AstroidValueError,
AttributeInferenceError,
InferenceError,
NameInferenceError,
Expand Down Expand Up @@ -441,6 +442,7 @@ def infer_subscript(
except (
AstroidTypeError,
AstroidIndexError,
AstroidValueError,
AttributeInferenceError,
AttributeError,
) as exc:
Expand Down
12 changes: 12 additions & 0 deletions astroid/nodes/node_classes.py
Expand Up @@ -22,6 +22,7 @@
from astroid.exceptions import (
AstroidIndexError,
AstroidTypeError,
AstroidValueError,
InferenceError,
NoDefault,
ParentMissingError,
Expand Down Expand Up @@ -234,6 +235,13 @@ def _container_getitem(instance, elts, index, context=None):
return new_cls
if isinstance(index, Const):
return elts[index.value]
except ValueError as exc:
raise AstroidValueError(
message="Slice {index!r} cannot index container",
node=instance,
index=index,
context=context,
) from exc
except IndexError as exc:
raise AstroidIndexError(
message="Index {index!s} out of range",
Expand Down Expand Up @@ -2030,6 +2038,10 @@ def getitem(self, index, context=None):
try:
if isinstance(self.value, (str, bytes)):
return Const(self.value[index_value])
except ValueError as exc:
raise AstroidValueError(
f"Could not index {self.value!r} with {index_value!r}"
) from exc
except IndexError as exc:
raise AstroidIndexError(
message="Index {index!r} out of range",
Expand Down
10 changes: 10 additions & 0 deletions tests/unittest_inference.py
Expand Up @@ -5316,6 +5316,16 @@ def test_slice_inference_in_for_loops_not_working() -> None:
assert inferred == util.Uninferable


def test_slice_zero_step_does_not_raise_ValueError() -> None:
node = extract_node("x = [][::0]; x")
assert next(node.infer()) == util.Uninferable


def test_slice_zero_step_on_str_does_not_raise_ValueError() -> None:
node = extract_node('x = ""[::0]; x')
assert next(node.infer()) == util.Uninferable


def test_unpacking_starred_and_dicts_in_assignment() -> None:
node = extract_node(
"""
Expand Down

0 comments on commit 50a7cd8

Please sign in to comment.