[Python-ideas] A general purpose range iterator (Re: improvements to slicing)

Ron Adam rrr at ronadam.com
Thu Oct 7 01:05:01 CEST 2010

On 10/06/2010 03:41 PM, Nick Coghlan wrote:
> On Thu, Oct 7, 2010 at 5:21 AM, Ron Adam<rrr at ronadam.com>  wrote:
>> I think these are easier to use than the current behavior.  It doesn't
>> change slices using positive indexes and steps so maybe it's not so backward
>> incompatible to sneak in.  ;-)
> I think that sound you just heard was thousands of SciPy users crying
> out in horror ;)

LOL, and my apologies to the SciPi users.

I did try to google to find routines where the stop and start indexes 
converge and result in an empty list as Spir suggested, but my google foo 
seems to be broken today.  Maybe someone can point me in the right google 

> Given a "do over", there a few things I would change about Python's
> range generation and extended slicing. Others would clearly change a
> few different things. Given the dual barriers of "rough consensus and
> running code", I don't think there are any *specific* changes that
> would make it through the gauntlet.

Yes, any changes would probably need to be done in a way that can be 
imported and live along side the current range and slice.

> The idea of a *generalised* range generator is in interesting one
> though. One that was simply:
> _d = object()
> def irange(start=_d, stop=_d, step=1, *, include_start=True,
> include_stop=False):
>      # Match signature of range while still allowing stop=val as the
> only keyword argument
>      if stop is _d:
>          start, stop = 0, start
>      elif start is _d:
>          start = 0
>      if include_start:
>          yield start
>      current = start
>      while 1:
>          current += step
>          if current>= stop:
>              break
>          yield current
>      if include_stop and current == stop:
>          yield stop
> Slower than builtin range() for the integer case, but works with
> arbitrary types (e.g. float, Decimal, datetime)

It wouldn't be that much slower if it returns another range object with the 
index's adjusted.  But then it wouldn't be able to use the arbitrary types.

A wild idea that keeps nudging my neurons is that sequence iterators or 
index objectes like slice objects could maybe be added before applying them 
to a final sequence.  Sort of an iter math.  It isn't as simple as just 
putting the iterators in a list and iterating the iterators in order, 
although that works for some things.


More information about the Python-ideas mailing list