slicing, mapping types, ellipsis etc.

Steven Bethard steven.bethard at gmail.com
Mon Nov 29 17:50:16 EST 2004


Jerry Sievers wrote:
> 1. what the Ellipsis object or ... syntax is used for
> 2. what a slice [..., j:k:l] does

My understanding is that the Ellipsis object is intended primarily for 
Numeric/numarray use.  Take a look at:

http://stsdas.stsci.edu/numarray/numarray-1.1.html/node26.html

> 3. how slices are applied to object of mapping types

The short answer is that they aren't.  Slices aren't hashable, so dicts 
can't handle them:

 >>> d = {}
 >>> d = {1:'a', 2:'b'}
 >>> d[1:2]
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
TypeError: unhashable type
 >>> hash(slice(1, 2))
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
TypeError: unhashable type

You can, however handle them if you write your own mapping type:

 >>> class M(object):
...     def __getitem__(self, x):
...         if isinstance(x, slice):
...             return x.start, x.stop, x.step
...         else:
...         	return x
...
 >>>
 >>> m = M()
 >>> m[1]
1
 >>> m[1:2]
(1, 2, None)

Hope this helps!

Steve



More information about the Python-list mailing list