[Python-ideas] Builtin infinite generator

Josiah Carlson jcarlson at uci.edu
Wed Mar 21 18:43:54 CET 2007


"Tobias Ivarsson" <thobes at gmail.com> wrote:
> Quite often I find myself wanting to write an infinite for-loop, or rather a
> loop with a counter, that terminates on some inner condition. Recently I
> even wanted to do this together with the generator comprehension syntax, I
> don't remember exactly what I wanted to do, but it was something like:
> zip( some_list_of_unknown_length, ('a' for x in infinit_generator) )
> I admit that my example is silly, but it still serves as an example of what
> I wanted to do.
> 
> Then I read that Ellipsis will become generally accepted in py3k [1] and
> thought why not let range accept ... as end-parameter to mean "until
> forever".
> 
> More silly examples to demonstrate how it would work:
> 
> >>> for i in range(...):
> ...     print i
> ...     if i == 4: break
[snip]
> Any thoughts on this?

It isn't reasonable in Python 2.x, as range() returns an actual list,
and an infinite list isn't reasonable.  It would be *possible* with
xrange() in Python 2.x, but then the question is "is such desireable?". 
The answer there is also no, as currently 2.x range() and xrange() are
limited by your platform int size (generally 32 bits)...

    >>> xrange(2**31)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    OverflowError: long int too large to convert to int
    >>> xrange(2**31-1)
    xrange(2147483647)
    >>>

In Python 3, ints and longs will be unified, so the whole 'limited by
platform int' shouldn't be applicable.  Further, xrange is renamed to
range.  So it becomes more reasonable.  On the other hand, a user (you)
should be able to give a *huge* value to range, and it would work as you
want ... to.  Generally, you are pretty safe with 2**64 * increment, but
if you are really anal, go with 2**128 * increment, that should keep you
safe until the big freeze.


Ultimately, -1.  It's not usable in Python 2.x, and Python 3.x will
support a variant trivially.

 - Josiah




More information about the Python-ideas mailing list