Skip to content

SliceView

Bases: PyoSequence[T]


              flowchart TD
              pyochain._sliceview.SliceView[SliceView]
              pyochain.abc._sequences.PyoSequence[PyoSequence]
              pyochain.abc._collection.PyoCollection[PyoCollection]
              pyochain.abc._iterable.PyoIterable[PyoIterable]
              pyochain.rs.Pipeable[Pipeable]
              pyochain.rs.Into[Into]
              pyochain.rs.Inspect[Inspect]
              pyochain.rs.Checkable[Checkable]
              pyochain.abc._collection.PyoContainer[PyoContainer]
              pyochain.abc._collection.PyoSized[PyoSized]
              pyochain.abc._sequences.PyoReversible[PyoReversible]

                              pyochain.abc._sequences.PyoSequence --> pyochain._sliceview.SliceView
                                pyochain.abc._collection.PyoCollection --> pyochain.abc._sequences.PyoSequence
                                pyochain.abc._iterable.PyoIterable --> pyochain.abc._collection.PyoCollection
                                pyochain.rs.Pipeable --> pyochain.abc._iterable.PyoIterable
                                pyochain.rs.Into --> pyochain.rs.Pipeable
                
                pyochain.rs.Inspect --> pyochain.rs.Pipeable
                

                pyochain.rs.Checkable --> pyochain.abc._iterable.PyoIterable
                

                pyochain.abc._collection.PyoContainer --> pyochain.abc._collection.PyoCollection
                
                pyochain.abc._collection.PyoSized --> pyochain.abc._collection.PyoCollection
                

                pyochain.abc._sequences.PyoReversible --> pyochain.abc._sequences.PyoSequence
                



              click pyochain._sliceview.SliceView href "" "pyochain._sliceview.SliceView"
              click pyochain.abc._sequences.PyoSequence href "" "pyochain.abc._sequences.PyoSequence"
              click pyochain.abc._collection.PyoCollection href "" "pyochain.abc._collection.PyoCollection"
              click pyochain.abc._iterable.PyoIterable href "" "pyochain.abc._iterable.PyoIterable"
              click pyochain.rs.Pipeable href "" "pyochain.rs.Pipeable"
              click pyochain.rs.Into href "" "pyochain.rs.Into"
              click pyochain.rs.Inspect href "" "pyochain.rs.Inspect"
              click pyochain.rs.Checkable href "" "pyochain.rs.Checkable"
              click pyochain.abc._collection.PyoContainer href "" "pyochain.abc._collection.PyoContainer"
              click pyochain.abc._collection.PyoSized href "" "pyochain.abc._collection.PyoSized"
              click pyochain.abc._sequences.PyoReversible href "" "pyochain.abc._sequences.PyoReversible"
            

A zero-copy, composable slice view over any collections::abc::Sequence.

A SliceView presents a live window into an existing sequence:

  • reads and writes reflect the underlying sequence
  • view-to-view slicing composes in O(1)
  • no data is copied unless explicitly requested.

Any object that implements __len__ and __getitem__ with integer indices is accepted

Credits
  • Original code and idea by @julianofischer in https://github.com/julianofischer/sliceview
  • Generically typed version by @hwelch-fle in https://github.com/hwelch-fle/sliceview which is what was used as the basis for this implementation.

No major changes besides linter/type-checker/docstring related-changes were made, besides the name (titled SliceView here instead of sliceview in the original repos).

And of course the pyochain integration with PyoSequence.

Parameters:

Name Type Description Default
base Sequence[T]

The underlying sequence.

required
start slice | int | None

Starting index of the view (inclusive). Defaults to 0.

None
stop int | None

Ending index of the view (exclusive). Has no effect if start is a slice.

None
step int | None

Step size for the view. Has no effect if start is a slice.

None

Examples:

>>> from pyochain import SliceView
>>> sv = SliceView([0, 1, 2, 3, 4, 5])
>>> sv[1:4].iter().collect()
Seq(1, 2, 3)
>>> sv[::2].iter().collect()
Seq(0, 2, 4)
>>> sv2 = sv[1:][::2]  # composed — O(1), no copy
>>> sv2.iter().collect()
Seq(1, 3, 5)
Source code in src/pyochain/_sliceview.py
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
class SliceView[T](PyoSequence[T]):  # noqa: PLW1641
    """A zero-copy, composable slice view over any `collections::abc::Sequence`.

    A `SliceView` presents a live window into an existing sequence:

    - reads and writes reflect the underlying sequence
    - view-to-view slicing composes in O(1)
    - no data is copied unless explicitly requested.

    Any object that implements `__len__` and `__getitem__` with integer indices is accepted

    Credits:
        - Original code and idea by @julianofischer in https://github.com/julianofischer/sliceview
        - Generically typed version by @hwelch-fle in https://github.com/hwelch-fle/sliceview which is what was used as the basis for this implementation.

        No major changes besides linter/type-checker/docstring related-changes were made, besides the name (titled `SliceView` here instead of `sliceview` in the original repos).

        And of course the pyochain integration with `PyoSequence`.

    Args:
        base (Sequence[T]): The underlying sequence.
        start (slice |int | None): Starting index of the view (inclusive). Defaults to 0.
        stop (int | None): Ending index of the view (exclusive). Has no effect if **start** is a `slice`.
        step (int | None): Step size for the view. Has no effect if **start** is a `slice`.

    Examples:
        ```python
        >>> from pyochain import SliceView
        >>> sv = SliceView([0, 1, 2, 3, 4, 5])
        >>> sv[1:4].iter().collect()
        Seq(1, 2, 3)
        >>> sv[::2].iter().collect()
        Seq(0, 2, 4)
        >>> sv2 = sv[1:][::2]  # composed — O(1), no copy
        >>> sv2.iter().collect()
        Seq(1, 3, 5)

        ```
    """

    _base: Sequence[T] | MutableSequence[T]
    _range: range | _OpenRange

    __slots__ = ("_base", "_range")  # pyright: ignore[reportUnannotatedClassAttribute, reportIncompatibleUnannotatedOverride]

    @overload
    def __init__(self, base: Sequence[T]) -> None: ...
    @overload
    def __init__(self, base: Sequence[T], start: slice) -> None: ...
    @overload
    def __init__(
        self,
        base: Sequence[T],
        start: int | None = None,
        stop: int | None = None,
        step: int | None = None,
    ) -> None: ...

    def __init__(
        self,
        base: Sequence[T],
        start: slice | int | None = None,
        stop: int | None = None,
        step: int | None = None,
    ) -> None:
        self._base = base
        if isinstance(start, slice):
            sl: slice = start
        else:
            sl = slice(start, stop, step)

        i_start, i_stop, i_step = sl.indices(len(base))

        # If the original stop was None, store an open sentinel so that the
        # view grows when elements are appended to the base.
        if sl.stop is None:  # pyright: ignore[reportAny]
            self._range = _OpenRange(i_start, i_step)
        else:
            self._range = range(i_start, i_stop, i_step)

    @classmethod
    def _from_range(cls, base: Sequence[T], r: range) -> SliceView[T]:
        sv = cls.__new__(cls)
        sv._base = base
        sv._range = r
        return sv

    @override
    def __iter__(self) -> Iterator[T]:
        base = self._base
        for i in self._current_range():
            yield base[i]

    @override
    def __contains__(self, item: object) -> bool:
        return any(item == el for el in self)

    @override
    def __reversed__(self) -> Iterator[T]:
        base = self._base
        return (base[i] for i in reversed(self._current_range()))

    @override
    def __eq__(self, other: object) -> bool:
        if isinstance(other, Sequence):
            return len(self) == len(other) and all(
                a == b for a, b in zip(self, other, strict=False)
            )
        return False

    @override
    def __repr__(self) -> str:
        cr = self._current_range()
        name = self.__class__.__name__
        return f"{name}({self._base!r})[{cr.start}:{cr.stop}:{cr.step}]"

    @override
    def __len__(self) -> int:
        return len(self._current_range())

    @overload
    def __getitem__(self, index: SupportsIndex) -> T: ...
    @overload
    def __getitem__(self, index: slice) -> SliceView[T]: ...
    @override
    def __getitem__(self, index: SupportsIndex | slice) -> SliceView[T] | T:
        if isinstance(index, slice):
            # Compose slices using Python's range slicing — O(1), exact.
            sub = self._current_range()[index]
            return self.__class__._from_range(self._base, sub)

        cr = self._current_range()
        length = len(cr)
        index = index.__index__()
        if index < 0:
            index += length
        if not (0 <= index < length):
            msg = "sliceview index out of range"
            raise IndexError(msg)
        return self._base[cr[index]]

    @overload
    def __setitem__(self, index: SupportsIndex, value: T) -> None: ...
    @overload
    def __setitem__(self, index: slice, value: Iterable[T]) -> None: ...
    def __setitem__(self, index: slice | SupportsIndex, value: T | Iterable[T]) -> None:
        match self._base, index:
            case MutableSequence(), slice():
                tr = self._current_range()[index]
                if abs(tr.step) != 1:
                    values: tuple[T, ...] = tuple(value)  # pyright: ignore[reportArgumentType, reportUnknownVariableType]
                    if len(values) != len(tr):
                        msg = f"attempt to assign sequence of size {len(values)} to slice of size {len(tr)}"
                        raise ValueError(msg)
                    for i, v in zip(tr, values, strict=False):
                        self._base[i] = v
                    return
                self._base[slice(tr.start, tr.stop, tr.step)] = value  # pyright: ignore[reportCallIssue, reportArgumentType]
                return
            case MutableSequence(), SupportsIndex():
                cr = self._current_range()
                length = len(cr)
                index = index.__index__()
                if index < 0:
                    index += length
                if not (0 <= index < length):
                    msg = "SliceView index out of range"
                    raise IndexError(msg)
                self._base[cr[index]] = value  # pyright: ignore[reportArgumentType, reportCallIssue]
            case _:
                msg = f"underlying sequence of type '{self._base.__class__}' has no '__setitem__'"
                raise TypeError(msg)

    def _current_range(self) -> range:
        """Return a concrete ``range`` clamped to the current base length."""
        r = self._range
        if isinstance(r, _OpenRange):
            return r.resolve(len(self._base))
        return r

    def advance(self, n: int) -> Self:
        """Shift the view's window forward by *n* index positions in-place.

        Args:
            n (int): Positions to advance (negative to retreat).

        Returns:
            Self: the view with its window advanced.

        Examples:
            This can be useful for sliding windows:

            ```python
            >>> from pyochain import SliceView, Range
            >>> data = Range(0, 10).iter().collect()
            >>> sv = SliceView(data, 0, 3)
            >>> sv.iter().collect()
            Seq(0, 1, 2)
            >>> sv.advance(3)
            SliceView(Seq(0, 1, 2, 3, 4, 5, 6, 7, 8, 9))[3:6:1]
            >>> sv.iter().collect()
            Seq(3, 4, 5)

            ```

        """
        b_len = len(self._base)
        cr = self._current_range()
        new_start = max(0, min(cr.start + n, b_len))
        delta = new_start - cr.start
        new_stop = max(0, min(cr.stop + delta, b_len))
        self._range = range(new_start, new_stop, cr.step)
        return self

    @property
    def base(self) -> Sequence[T] | MutableSequence[T]:
        """The underlying sequence this view points into.

        Returns:
            Sequence[T] | MutableSequence[T]: The underlying sequence.

        Examples:
            ```python
            >>> from pyochain import SliceView
            >>> data = [1, 2, 3, 4, 5]
            >>> sv = SliceView(data)[1:4]
            >>> sv.base is data
            True

            ```

        """
        return self._base

base property

The underlying sequence this view points into.

Returns:

Type Description
Sequence[T] | MutableSequence[T]

Sequence[T] | MutableSequence[T]: The underlying sequence.

Examples:

>>> from pyochain import SliceView
>>> data = [1, 2, 3, 4, 5]
>>> sv = SliceView(data)[1:4]
>>> sv.base is data
True

advance(n)

Shift the view's window forward by n index positions in-place.

Parameters:

Name Type Description Default
n int

Positions to advance (negative to retreat).

required

Returns:

Name Type Description
Self Self

the view with its window advanced.

Examples:

This can be useful for sliding windows:

>>> from pyochain import SliceView, Range
>>> data = Range(0, 10).iter().collect()
>>> sv = SliceView(data, 0, 3)
>>> sv.iter().collect()
Seq(0, 1, 2)
>>> sv.advance(3)
SliceView(Seq(0, 1, 2, 3, 4, 5, 6, 7, 8, 9))[3:6:1]
>>> sv.iter().collect()
Seq(3, 4, 5)
Source code in src/pyochain/_sliceview.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
def advance(self, n: int) -> Self:
    """Shift the view's window forward by *n* index positions in-place.

    Args:
        n (int): Positions to advance (negative to retreat).

    Returns:
        Self: the view with its window advanced.

    Examples:
        This can be useful for sliding windows:

        ```python
        >>> from pyochain import SliceView, Range
        >>> data = Range(0, 10).iter().collect()
        >>> sv = SliceView(data, 0, 3)
        >>> sv.iter().collect()
        Seq(0, 1, 2)
        >>> sv.advance(3)
        SliceView(Seq(0, 1, 2, 3, 4, 5, 6, 7, 8, 9))[3:6:1]
        >>> sv.iter().collect()
        Seq(3, 4, 5)

        ```

    """
    b_len = len(self._base)
    cr = self._current_range()
    new_start = max(0, min(cr.start + n, b_len))
    delta = new_start - cr.start
    new_stop = max(0, min(cr.stop + delta, b_len))
    self._range = range(new_start, new_stop, cr.step)
    return self