index out of range with slice object

Peter Otten __peter__ at web.de
Thu Mar 11 08:29:57 CET 2004


Uwe Mayer wrote:

> a class of mine should support the list interface and implements the
> __len__ and __getitem__ methods.
> 
> Now when I ask for an unbounded slice:
> 
>>>> len( myObj[:] )
> 
> my __getitem__(self, y) method gets called with
> 
>     y = slice(0, 2147483647, None)
> 
> Now step size is ok, but where does that incredibly large stop index come
> from? Also I expected the start index rather to be None than zero.
> The __len__(self) method returns the correct length, which is 728.
> 
> Has anybody encountered something like that bevore? Is that natural or am
> I doing something wrong?

There seems a transition to be going on, due to extended slices, I suppose:

>>> class Old:
...     def __getitem__(self, index):
...             return index
...
>>> class New(object):
...     def __getitem__(self, index):
...             return index
...
>>> New()[:]
slice(None, None, None)
>>> Old()[:]
slice(0, 2147483647, None)
>>>

I found only the old style behaviour documented in the reference manual
http://www.python.org/doc/current/ref/slicings.html:

"The lower and upper bound expressions, if present, must evaluate to plain
integers; defaults are zero and the sys.maxint, respectively."

So "incredibly large" is in fact sys.maxint, which should be obvious if you
convert it to hexadecimal:

>>> hex(2147483647)
'0x7fffffff'

Anyway, you can use the indices() method to get the actual boundaries in
both cases:

>>> Old()[:].indices(10)
(0, 10, 1)
>>> New()[:].indices(10)
(0, 10, 1)
>>>

Peter



More information about the Python-list mailing list