Skip to content

Commit

Permalink
Change ZTUtils.Lazy to support slicing via _getitem__.
Browse files Browse the repository at this point in the history
`__getslice__` is deprecated since Python 2.0 :))

This adds support for extended slicing and the step argument. A lot
of the classes defer to one common implementation for slicing support
in the abstract Lazy subclass, but continue to implement their own
efficient single key lookup.
  • Loading branch information
hannosch committed May 15, 2017
1 parent 1951b73 commit f4f0f23
Showing 1 changed file with 28 additions and 15 deletions.
43 changes: 28 additions & 15 deletions src/ZTUtils/Lazy.py
Expand Up @@ -11,7 +11,7 @@
#
##############################################################################

from itertools import islice, count
from six.moves import xrange

_marker = object()

Expand Down Expand Up @@ -56,16 +56,20 @@ def __add__(self, other):
"Can not concatenate objects. Both must be lazy sequences.")
return LazyCat([self, other])

def __getslice__(self, i1, i2):
r = []
for i in islice(count(i1), i2 - i1):
try:
r.append(self[i])
except IndexError:
return r
return r
def __getitem__(self, index):
if isinstance(index, slice):
r = []
start, stop, step = index.indices(len(self))
for i in xrange(start, stop, step):
try:
r.append(self[i])
except IndexError:
return r
return r

slice = __getslice__
# The single key lookup is implemented in the subclasses.
raise NotImplementedError(
'Lazy subclasses must implement __getitem__.')


class LazyCat(Lazy):
Expand Down Expand Up @@ -108,6 +112,9 @@ def __init__(self, sequences, length=None, actual_result_count=None):
self.actual_result_count = flattened_count

def __getitem__(self, index):
if isinstance(index, slice):
return super(LazyCat, self).__getitem__(index)

data = self._data
try:
seq = self._seq
Expand Down Expand Up @@ -184,6 +191,9 @@ def __init__(self, func, seq, length=None, actual_result_count=None):
self.actual_result_count = self._len

def __getitem__(self, index):
if isinstance(index, slice):
return super(LazyMap, self).__getitem__(index)

data = self._data
if index in data:
return data[index]
Expand All @@ -204,6 +214,9 @@ def __init__(self, test, seq):
self._test = test

def __getitem__(self, index):
if isinstance(index, slice):
return super(LazyFilter, self).__getitem__(index)

data = self._data
try:
s = self._seq
Expand Down Expand Up @@ -252,6 +265,9 @@ def __init__(self, test, seq):
self._test = test

def __getitem__(self, index):
if isinstance(index, slice):
return super(LazyMop, self).__getitem__(index)

data = self._data
try:
s = self._seq
Expand Down Expand Up @@ -304,9 +320,6 @@ def __len__(self):
return self._len

def __getitem__(self, index):
if isinstance(index, slice):
return self.__class__(self._seq[index])
return self._seq[index][1]

def __getslice__(self, start, end):
return self.__class__(self._seq[start:end])

slice = __getslice__

0 comments on commit f4f0f23

Please sign in to comment.