Skip to content

Commit

Permalink
support slice assignment in ListConfig (omry#736)
Browse files Browse the repository at this point in the history
  • Loading branch information
pixelb committed Feb 1, 2022
1 parent 7288a5a commit c25bb9c
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
18 changes: 17 additions & 1 deletion omegaconf/listconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,23 @@ def _set_at_index(self, index: Union[int, slice], value: Any) -> None:

def __setitem__(self, index: Union[int, slice], value: Any) -> None:
try:
self._set_at_index(index, value)
if isinstance(index, slice):
_ = iter(value) # check iterable
indexes = range(*index.indices(len(self)))
if index.step is not None:
# Extended slice assignment lengths must match
if len(indexes) != len(value):
raise ValueError(
f"attempt to assign sequence of size {len(value)} to extended slice of size {len(indexes)}"
)
for val_i, i in enumerate(indexes):
del self[i]
self.insert(i, value[val_i])
for val_i in range(val_i + 1, len(value)):
i += 1
self.insert(i, value[val_i])
else:
self._set_at_index(index, value)
except Exception as e:
self._format_and_raise(key=index, value=value, cause=e)

Expand Down
20 changes: 20 additions & 0 deletions tests/test_basic_ops_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -845,6 +845,26 @@ def test_getitem_slice(sli: slice) -> None:
assert olst.__getitem__(sli) == expected


def test_setitem_slice() -> None:
cfg = OmegaConf.create(["a", "b", "c", "d"])
# slice assignment, same number elements
assert cfg == ["a", "b", "c", "d"]
cfg[1:3] = ["x", "y"]
assert cfg == ["a", "x", "y", "d"]
# slice assignment, extra elements
cfg[1:3] = ["x", "y", "z"]
assert cfg == ["a", "x", "y", "z", "d"]
# Extended slice assignment
cfg[1:3:1] = ["x", "y"]
assert cfg == ["a", "x", "y", "z", "d"]
# Non iterable
with raises(TypeError):
cfg[1:3] = 1
# Extended slice length mismatch
with raises(ValueError):
cfg[1:3:1] = ["x", "y", "z"]


@mark.parametrize(
"lst,idx,expected",
[
Expand Down

0 comments on commit c25bb9c

Please sign in to comment.