revive a generator

Ian Kelly ian.g.kelly at gmail.com
Fri Oct 21 10:25:22 EDT 2011


On Fri, Oct 21, 2011 at 2:02 AM, Yingjie Lan <lanyjie at yahoo.com> wrote:
> Oops, my former reply has the code indentation messed up
> by the mail system. Here is a reformatted one:
>
>
> What if the generator involves a variable from another scope,
> and before re-generating, the variable changed its value.
> Also, the generator could be passed in as an argument,
> so that we don't know its exact expression.

In the former case, use a named generator function and call it twice
to create two generators.  In the latter case, don't pass in the
generator as an argument.  Pass in a callable that constructs the
iterator instead.  Modifying your example:

vo = 34
def mygen():
    for x in range(3):
        yield vo * x

def myfun(g):
    global vo
    for i in g(): print(i)
    vo += 3
    for i in g(): print(i)

myfun(mygen)

Cheers,
Ian



More information about the Python-list mailing list