revive a generator

Paul Rudin paul.nospam at rudin.co.uk
Fri Oct 21 04:17:48 EDT 2011


Yingjie Lan <lanyjie at yahoo.com> writes:

>
>
> 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.
>
>>>> vo = 34
>>>> g = (vo*x for x in range(3))
>>>> def myfun(g):
>             for i in g: print(i)
>             vo  += 3
>             revive(g) #best if revived automatically
>             for i in g: print(i)
>>>> myfun(g)
>
>


I'm not really sure whether you intend g to yield the original values
after your "revive" or new values based on the new value of vo.  But
still you can make a class that supports the iterator protocol and does
whatever you want (but you can't use the generator expression syntax).

If you want something along these lines you should probably read up on
the .send() part of the generator protocol.

As an aside you shouldn't really write code that uses a global in that
way.. it'll end up biting you eventually.

Anyway... we can speculate endlessly about non-existent language
constructs, but I think we've probably done this one to death.



More information about the Python-list mailing list