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.
None that doesn't internally use another infinite iterator defined as a class/function/generator (not -expression, a function with
yield
). A generator expression always draws from anoter iterable and does nothing but filtering and mapping its items. You can't go from finite items to infinite ones with onlymap
andfilter
, you needwhile
(or afor
that doesn't terminate, which is exactly what we can't have using onlyfor
and finite iterators).Trivia: PEP 3142 is superficially similar, but upon closer inspection it seems that it still requires the
for
clause (so no(0 while True)
for you), i.e. only provides a shortcut foritertools.takewhile
.Quite ugly and crazy (very funny however), but you can build your own iterator from an expression by using some tricks (without "polluting" your namespace as required):
you can iterate over a callable returning a constant always different than iter()'s sentinel
iter
= zero-argument callable + sentinel valueint()
always returns0
Therefore,
iter(int, 1)
is an infinite iterator. There are obviously a huge number of variations on this particular theme (especially once you addlambda
into the mix). One variant of particular note isiter(f, object())
, as using a freshly created object as the sentinel value almost guarantees an infinite iterator regardless of the callable used as the first argument.(as some mentioned, thanks to python documentation https://docs.python.org/2/library/itertools.html#itertools.cycle)
Your OS may provide something that can be used as an infinite generator. Eg on linux
obviously this is not as efficient as