index out of range with slice object

Peter Otten __peter__ at web.de
Thu Mar 11 02:41:42 EST 2004


Peter Otten wrote:

> 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:

Ok, read it again:

"The semantics for an extended slicing are as follows. [...] The conversion
of a proper slice is a slice object (see section 3.2) whose start, stop and
step attributes are the values of the expressions given as lower bound,
upper bound and stride, respectively, substituting None for missing
expressions."

> 
> "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