[Python-Dev] Xrange and Slices
Oren Tirosh
oren-py-d@hishome.net
Sun, 30 Jun 2002 13:39:03 -0400
On Wed, Jun 26, 2002 at 02:37:17AM -0400, Raymond Hettinger wrote:
> Wild idea of the day:
> Merge the code for xrange() into slice().
There's a patch pending for this: www.python.org/sf/575515
Some issues related to the change:
xrange currently accepts only integer arguments. With this change it
will accept any type and the exception will be raised when iteration is
attempted. Is this a problem? The canonical use of xrange is to use it
immediately in a for statement so it will probably go unnoticed.
Should xrange be an alias for slice or the other way around? Personally
I think that xrange is the more familiar of the two so the merged object
should be called xrange. Its repr should also be like that of xrange,
suppressing the display of unnecessary None arguments.
One of the differences between slice and xrange is that slices are allowed
to have open-ended ranges such as slice(10, None). It may useful (and
probably quite controversial...) to allow open-ended xranges too, defaulting
to INT_MAX or INT_MIN, depending on the sign of the step. It's useful in
for loops where you know you will bail out with break and also for zip.
A possible extension is to add a method iterslice(len) to slice/xrange that
exposes the functionality of PySlice_GetIndicesEx. With this change the
following code should work correctly for all forms of slicing:
def __getitem__(self, index):
if isinstance(index, xrange):
return [self[i] for i in index.iterslice(len(self))]
else:
... implement integer indexing for this container class
This extension, BTW, is independent of whether slice/xrange merging is
accepted or not.
Oren