Co-routines

thewrights at ozemail.com.au thewrights at ozemail.com.au
Thu Jul 17 09:07:36 EDT 2003


I have an application in which I want the users to be able to create python
functions:

def f1():
    print "1-1"
    print "1-2"
    print "1-3"

def f2():
    print "2-1"
    print "2-2"
    print "3-3"

and when my application runs, I want to execute these functions in
"lock-step", so that the output looks like:

    1-1
    2-2
    1-2
    2-2
    1-3
    2-3

If I were using prolog I'd write a meta-interpreter; with lisp/scheme I
might use macros and do some source-code transformation.

What's the most Pythonic way to do this?

If I assume that each statement in the function bodies occupy only one
physical line, I could read the user functions in, and output them to a new
file, interspersing "yield"s. If, quite reasonable, a user spans a statement
over more that one line:

def f3():
    d = {
            "a" : "One string",
            "b" : "Another string"
            }
    print d

then I'm in the "parsing python" game.

(I recall the malevolent and  wicked ternary operator example that was
posted here which fiddled with function source code in the metaclass... I'm
still picking up pieces of my brain from the floor)

I'd be very grateful for suggestions. Is the compiler module my friend?

I would love to end up with:

while 1:
    try:
        for f in function_list:
            f.next()
    except StopIteration:
        print "wow!"


Thanks

Chris Wright






More information about the Python-list mailing list