[Python-Dev] Xrange and Slices

Oren Tirosh oren-py-d@hishome.net
Fri, 12 Jul 2002 21:21:05 +0300


On Fri, Jul 12, 2002 at 01:09:32PM -0400, Guido van Rossum wrote:
> [Raymond Hettinger]
> > > Merge the code for xrange() into slice().
> 
> [Oren Tirosh]
> > There's a patch pending for this: www.python.org/sf/575515
> 
> I've rejected this.  It's better to let these two be different, so
> that it's clear what the intended use is.

When I was going through the sources of sliceobject.c I found the function 
PySlice_GetIndicesEx.  It performs the magic of trimming a slice into the 
range of indices of a sequence, including negative indices and intervals 
with None as start or stop value.  A comment in this function says:

 /* this is harder to get right than you might think */

Wouldn't it be a good idea to expose this nontrivial functionality to 
Python code as a method of slice objects?  The method would take an integer 
argument (length) and return an xrange object.  It should make it much 
easier to implement user types that support extended slicing:

    def __getitem__(self, index):
        if isinstance(index, slice):
            return [get_item_at(i) for i in index.trim(len(self))]
        else:
            return get_item_at(index)

Suggestions for a better name than trim?  Any reason why this API should 
stay exposed only to C and not to Python?

	Oren