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

Nick Coghlan ncoghlan at gmail.com
Wed Oct 6 22:41:21 CEST 2010

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 ;)

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.

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,
    # 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:
        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)


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list