Generator Frustration
Thomas Rachel
nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Mon Jun 6 05:07:53 EDT 2011
Am 04.06.2011 20:27 schrieb TommyVee:
> I'm using the SimPy package to run simulations. Anyone who's used this
> package knows that the way it simulates process concurrency is through
> the clever use of yield statements. Some of the code in my programs is
> very complex and contains several repeating sequences of yield
> statements. I want to combine these sequences into common functions.
Which are then generators.
> The problem of course, is that once a yield gets put into a function,
> the function is now a generator and its behavior changes.
Isn't your "main" function a generator as well?
> Is there any elegant way to do this? I suppose I can do things like
> ping-pong yield statements, but that solutions seems even uglier than
> having a very flat, single main routine with repeating sequences.
I'm not sure if I got it right, but I think you could emulate this
"yield from" with a decorator:
def subgen1(): yield 1; yield 2;
def subgen2(): yield 1; yield 2;
Instead of doing now
def allgen():
for i in subgen1(): yield i
for i in subgen2(): yield i
you as well could do:
def yield_from(f):
def wrapper(*a, **k):
for sub in f(*a, **k):
for i in sub:
yield i
return wrapper
@yield_from
def allgen():
yield subgen1()
yield subgen2()
(Untested.)
Thomas
More information about the Python-list
mailing list