Is there an expression for an infinite generator?

hugomg picture hugomg · Apr 21, 2011 · Viewed 60.2k times · Source

Is there a straight-forward generator expression that can yield infinite elements?

This is a purely theoretical question. No need for a "practical" answer here :)


For example, it is easy to make a finite generator:

my_gen = (0 for i in xrange(42))

However, to make an infinite one I need to "pollute" my namespace with a bogus function:

def _my_gen():
    while True:
        yield 0
my_gen = _my_gen()

Doing things in a separate file and import-ing later doesn't count.


I also know that itertools.repeat does exactly this. I'm curious if there is a one-liner solution without that.

Answer

Katriel picture Katriel · Apr 21, 2011

itertools provides three infinite generators:

I don't know of any others in the standard library.


Since you asked for a one-liner:

__import__("itertools").count()