[Python-ideas] Pass a function as the argument "step" of range()

Pierre Quentel pierre.quentel at gmail.com
Thu Jul 2 08:30:53 CEST 2015


In languages such as Javascript, the incrementation of a for loop counter
can be done by an operation, for instance :

for(i=1; i<N; i*=2)

would iterate on the powers of 2 lesser than N.

To achieve the same thing in Python we currently can't use range() because
it increments by an integer (the argument "step"). An option is to build a
generator like :

def gen(N):
    i = 1
    while i<=N:
        yield i
        i *= 2

then we can iterate on gen(N).

My proposal is that besides an integer, range() would accept a function as
the "step" argument, taking the current counter as its argument and
returning the new counter value. Here is a basic pure-Python implementation
:

import operator

class Range:

    def __init__(self, start, stop, incrementor):
        self.start, self.stop = start, stop
        self.incrementor = incrementor
        # Function to compare current counter and stop value : <= or >=
        self.comp = operator.ge if self.stop>self.start else operator.le
        self.counter = None

    def __iter__(self):
        return self

    def __next__(self):
        if self.counter is None:
            self.counter = self.start
        else:
            self.counter = self.incrementor(self.counter)
        if self.comp(self.counter, self.stop):
            raise StopIteration
        return self.counter

Iterating on the powers of 2 below N would be done by :

for i in Range(1, N, lambda x:x*2)

I haven't seen this discussed before, but I may not have searched enough.

Any opinions ?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150702/170320ca/attachment.html>


More information about the Python-ideas mailing list