# HG changeset patch # User Paul Boddie # Date 1480631243 -3600 # Node ID cb64d3e04c11a436e3d4a3386ae3dc3e529527d7 # Parent 79c82d827bbe2cefa22606bfb682810ee8802731 Supported Sliceobj usage, introduced slice step information to __getslice__. Added tests involving slices. diff -r 79c82d827bbe -r cb64d3e04c11 lib/__builtins__/sequence.py --- a/lib/__builtins__/sequence.py Thu Dec 01 23:06:26 2016 +0100 +++ b/lib/__builtins__/sequence.py Thu Dec 01 23:27:23 2016 +0100 @@ -49,7 +49,7 @@ # Handle slices separately. elif _isinstance(index, slice): - return self.__getslice__(index.start, index.end) + return self.__getslice__(index.start, index.end, index.step) # No other kinds of objects are supported as indexes. @@ -77,9 +77,16 @@ else: raise TypeError() - def __getslice__(self, start, end=None): + def __getslice__(self, start, end=None, step=1): - "Return a slice starting from 'start', with the optional 'end'." + """ + Return a slice of the sequence starting from the 'start' index, ending + before the optional 'end' (or at the end of the sequence), and providing + items at the frequency given by 'step' (with a default step of 1). + """ + + if step == 0: + raise ValueError(step) length = self.__len__() @@ -101,9 +108,9 @@ result = [] - while start < end: + while step > 0 and start < end or step < 0 and start > end: result.append(self.__get_single_item__(start)) - start += 1 + start += step return result diff -r 79c82d827bbe -r cb64d3e04c11 lib/operator/__init__.py --- a/lib/operator/__init__.py Thu Dec 01 23:06:26 2016 +0100 +++ b/lib/operator/__init__.py Thu Dec 01 23:27:23 2016 +0100 @@ -80,4 +80,6 @@ pos, ) +from __builtins__.span import slice # for Sliceobj instantiation + # vim: tabstop=4 expandtab shiftwidth=4 diff -r 79c82d827bbe -r cb64d3e04c11 tests/slice.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tests/slice.py Thu Dec 01 23:27:23 2016 +0100 @@ -0,0 +1,12 @@ +l = range(0, 10) +print l # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + +s = slice(2, 5) +print s # __builtins__.span.slice(2, 5, 1) + +print l[s] # [2, 3, 4] +print l[2:5] # [2, 3, 4] +print l[2:5:-1] # [] +print l[5:2:-1] # [5, 4, 3] +print l[1:9:2] # [1, 3, 5, 7] +print l[9:1:-2] # [9, 7, 5, 3]