Created
May 31, 2018 05:44
-
-
Save PythonCHB/7e54d511700af31e305887d2c5e006d2 to your computer and use it in GitHub Desktop.
slice iterator
This file contains 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
#!/usr/bin/env python3 | |
""" | |
islice mixin -- makes an easy to access slice-style iterator | |
""" | |
class slice_list(list): | |
@property | |
def islice(self): | |
return ISlice(self) | |
class islice_mixin: | |
@property | |
def islice(self): | |
return ISlice(self) | |
class ISlice: | |
""" | |
mixin that adds an iterable acces with slice semantics | |
""" | |
def __init__(self, seq): | |
self.seq = seq | |
def __iter__(self): | |
self.current = self.start - self.stride | |
return self | |
def __next__(self): | |
print("in next") | |
self.current += self.stride | |
if ((self.stride > 0 and self.current >= self.stop) or | |
(self.stride < 0 and self.current <= self.stop)): | |
raise StopIteration | |
return self.seq[self.current] | |
def __getitem__(self, slc): | |
print("in index") | |
print(slc) | |
if not isinstance(slc, slice): | |
raise TypeError(".islice only works with single slices") | |
self.start, self.stop, self.stride = slc.indices(len(self.seq)) | |
print(self.start, self.stop, self.stride) | |
return self |
This file contains 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
""" | |
test code for islice | |
""" | |
import pytest | |
from islice import ISlice, slice_list, islice_mixin | |
@pytest.fixture | |
def simple_list(): | |
return slice_list([2, 4, 3, 5, 6, 7, 3, 8, 2]) | |
@pytest.fixture | |
def tuple_mixedin(): | |
class slice_tuple(tuple, islice_mixin): | |
pass | |
return slice_tuple((4, 6, 2, 8, 3, 5, 6)) | |
def test_islice(): | |
isl = ISlice([1, 2, 3]) | |
slicer = isl[:] | |
print(slicer) | |
def test_slice_list1(simple_list): | |
l2 = [] | |
for i in simple_list.islice[:]: | |
print(i) | |
l2.append(i) | |
assert l2 == simple_list | |
def test_slice_simple_index(simple_list): | |
with pytest.raises(TypeError): | |
simple_list.islice[4] | |
def test_slice_stride(simple_list): | |
result = list(simple_list.islice[::2]) | |
assert result == simple_list[::2] | |
def test_slice_negative(simple_list): | |
result = list(simple_list.islice[::2]) | |
assert result == simple_list[::2] | |
def test_slice_reverse(simple_list): | |
result = list(simple_list.islice[::-1]) | |
assert result == simple_list[::-1] | |
def test_mixedin(tuple_mixedin): | |
result = tuple(tuple_mixedin[:2:-1]) | |
assert result == tuple_mixedin[:2:-1] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment