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

Ron Adam ron3200 at gmail.com
Tue Oct 29 05:49:01 CET 2013



On 10/27/2013 12:04 PM, Guido van Rossum wrote:
> Are we stuck with this forever? If we want to fix this in Python 4 we'd
> have to start deprecating negative stride with non-empty lower/upper bounds
> now. And we'd have to start deprecating negative step for range()
> altogether, recommending reversed(range(lower, upper)) instead.
>
> Thoughts? Is NumPy also affected?

I found this very short but interesting page that explains a little bit 
about how NumPy uses Python's slices.

     http://ilan.schnell-web.net/prog/slicing/

It looks like as long as we don't change the semantics of how slice objects 
get passed it won't effect NumPy.

Using the example from the web page above, we can see how the slice syntax 
already excepts more than one set of index's and/or values separated by 
commas.   ;-)

 >>> class foo:
...    def __getitem__(self, *args):
...       print(args)
...
 >>> x = foo()

 >>> x[2:3, 4:5]
((slice(2, 3, None), slice(4, 5, None)),)


It looks like it's the __getitem__ and __setitem__ methods that complains 
if you send it more than one set of indices or value.  It's not a syntax 
limitation.

If the left and right indices are to be considered separate from the step, 
we can use this existing legal syntax, and just pass the step after a comma.

     a[i:j, k]

And teach __getitem__ and __setitem__ to take the extra value.

Then your proposed relationship becomes the following and it's even clearer 
that (i and j) are separate and not effected by k.

     a[i:j, k] == a[i:j][:, k]


 >>> i, j, k = 0, 9, -1


 >>> x[i:j, k]
((slice(0, 9, None), -1),)

 >>> x[i:j]
(slice(0, 9, None),)

 >>> x[:, k]
((slice(None, None, None), -1),)


Cheers,
   Ron



More information about the Python-ideas mailing list