[Tutor] 'slice', etc
eryksun
eryksun at gmail.com
Sun Dec 8 04:28:59 CET 2013
On Sat, Dec 7, 2013 at 9:01 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> For the record, slice objects existed in Python 1.5, so they have been
> around and used for extended (three argument) slicing for a long time.
> It's only the two argument slicing that called __getslice__.
According to the NEWS for 1.4b2 (1996), slice objects and Ellipsis
were added to support Jim Hugunin's Numeric, the ancestor of NumPy.
http://hg.python.org/cpython/file/129f1299d4e9/Misc/NEWS
Here's the 1.4 slice/ellipsis implementation by Jim Hugunin and Chris Chase:
http://hg.python.org/cpython/file/129f1299d4e9/Objects/sliceobject.c
In NumPy, Ellipsis is used to insert as many ':' as needed based on
the array shape. For example:
>>> import numpy as np
>>> a = np.reshape(np.arange(8), (1,2,2,2))
>>> a
array([[[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]]])
>>> a[:,:,:,1]
array([[[1, 3],
[5, 7]]])
>>> a[...,1]
array([[[1, 3],
[5, 7]]])
Naturally the comma in the above examples creates a tuple:
class Test(object):
def __getitem__(self, key):
return key, type(key)
>>> Test()[:,1]
((slice(None, None, None), 1), <type 'tuple'>)
>>> Test()[...,1]
((Ellipsis, 1), <type 'tuple'>)
More information about the Tutor
mailing list