In Numpy (and Python in general, I suppose), how does one store a slice-index, such as (...,0,:), in order to pass it around and apply it to various arrays? It would be nice to, say, be able to pass a slice-index to and from functions.

5 Answers
5

Python creates special objects out of the slice syntax, but only inside the square brackets for indexing. You can either create those objects by hand (in this case, (...,0,:) is (Ellipsis, 0, slice(None, None, None)), or you can create a little helper object:

This directly solves the problem, assuming you don't actually care about the representation or what it means because you're just going to pass it around to use in Numpy. I had the same thought basically, but showed how to dig in and figure out what everything is :)
–
Karl KnechtelJul 22 '11 at 20:36

The neat thing about Python is that you can actually make a class to inspect how these things are represented. Python uses the magic method __getitem__ to handle indexing operations, so we'll make a class that overloads this to show us what was passed in, instantiate the class, and "index in" to the instance: