Generator Frustration

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Jun 4 20:56:51 EDT 2011


On Sat, 04 Jun 2011 14:27:32 -0400, TommyVee wrote:

> 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. 
> The problem of course, is that once a yield gets put into a function,
> the function is now a generator and its behavior changes.  Is there any
> elegant way to do this?


I don't quite understand the nature of your problem, but it seems to me 
that it is easily solved by simply not using yield in the common 
functions. Instead of:


def main():
    for x in sequence:
        if a:
            y = a+b+c+d+e
            yield y
        elif b:
            y = a+b+c+d+f
            yield y
        else:
            y = a+b+c+d
            yield y+1

(where each of the lines y = ... is meant to be a big block of mostly 
common code), factor out the similar parts into one or more external 
functions:

def f(a, b, c, d):
    return a+b+c+d  # big block of common code

def main():
    for x in sequence:
        if a:
            y = f(a, b, c, d)  # call the common part
            y += e
            yield y
        elif b:
            y = f(a, b, c, d)
            y += f
            yield y
        else:
            y = f(a, b, c, d)
            y += 1
            yield y


If this is not what you're talking about, an example may help.


> I suppose I can do things like ping-pong yield statements, 

I have no idea what you think that means, but another alternative is to 
loop over the generator output and re-yield it:

        for x in f():
            yield x

A nice piece of syntax that has been proposed for Python is "yield from", 
which will do the same thing, but you can't use that yet.


-- 
Steven



More information about the Python-list mailing list