[Python-ideas] Where did we go wrong with negative stride?

Joshua Landau joshua at landau.ws
Mon Oct 28 22:19:32 CET 2013


On 28 October 2013 21:06, Joshua Landau <joshua at landau.ws> wrote:
> On 28 October 2013 17:15, Joshua Landau <joshua at landau.ws> wrote:
>> <suggested using "~" instead of "-">
>
> # Here's a quick mock-up of my idea.
>
> class NotSliced(list):
...

# And a minor bugfix and correction:

class NotSliced(list):
    def __getitem__(self, itm):
        if isinstance(itm, slice):
            start, stop, step = itm.start, itm.stop, itm.step

            if step  is None: step  = 1
            if start is None: start = ~0 if step < 0 else  0
            if stop  is None: stop  =  0 if step < 0 else ~0

            if start < 0: start += len(self) + 1
            if stop  < 0: stop  += len(self) + 1

            if step > 0:
                return NotSliced(super().__getitem__(slice(start, stop, step)))

            else:
                return NotSliced(super().__getitem__(slice(stop,
start))[::step])

        else:
            return super().__getitem__(itm)

ns = NotSliced([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

# This came out wrong last time. I should be more careful...
ns[~4:~0][::-1]
ns[~0:~4:-1]
#>>> [9, 8, 7, 6]
#>>> [9, 8, 7, 6]

ns[~4:~0][::-2]
ns[~0:~4:-2]
#>>> [9, 7]
#>>> [9, 7]


More information about the Python-ideas mailing list