Last active
June 20, 2023 12:01
-
-
Save 3noch/b5f3175cfe39aea71ca4d07469570047 to your computer and use it in GitHub Desktop.
ListView.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ListView(): | |
def __init__(self, items, slice_=None): | |
start = (slice_.start if slice_ else None) or 0 | |
stop = (slice_.stop if slice_ else None) or float('inf') | |
step = (slice_.step if slice_ else None) or 1 | |
if isinstance(items, ListView): | |
self._items = items._items | |
self._start = max(items._start, items._start + start) | |
self._stop = min(items._stop, items._start + stop) | |
self._step = items._step * step | |
else: | |
self._items = items | |
self._start = start | |
self._stop = stop | |
self._step = step | |
def __getitem__(self, key): | |
if isinstance(key, slice): | |
return ListView(self, key) | |
return self._items[self._start + key * self._step] | |
def __iter__(self): | |
return (self._items[i] for i in range(self._start or 0, len(self._items) if self._stop == float('inf') else self._stop, self._step)) | |
def __len__(self): | |
return (min(len(self._items), self._stop) - self._start) // self._step |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One thing we could do to make this more flexible is not use
len
and indexing in__iter__
. Instead we could iterate and skip_step
items. We'd have to keep around some sort of pointer to the first item to start iterating over. That would allow us to slice into things like generators!