python: iterator from a function

python

Solution

You want an iterator which continuously yields values until you stop asking it for new ones? Simply use

it = iter(function, sentinel)

which calls `function()` for each iteration step until the result `== sentinel`.

So choose a sentinel which can never be returned by your wanted function, such as `None`, in your case.

rand_iter = lambda start, end: iter(random.randint(start, end), None)
rand_bytes = rand_iter(0, 256)

If you want to monitor some state on your machine, you could do

iter_mystate = iter(getstate, None)

which, in turn, infinitely calls `getstate()` for each iteration step.

But beware of functions returning `None` as a valid value! In this case, you should choose a sentinel which is guaranteed to be unique, maybe an object created for exactly this job:

iter_mystate = iter(getstate, object())

Problem

What is an idiomatic way to create an infinite iterator from a function? For example ``` from itertools import islice import random rand_characters = to_iterator( random.randint(0,256) ) print ' '.join( islice( rand_characters, 100)) ``` would produce 100 random numbers

Original source

Related problems