Co-routines

Michele Simionato mis6 at pitt.edu
Fri Jul 18 14:54:40 CEST 2003


If really you want to play tricks with the source code, as Micheal
Spark is suggesting, you can avoid generators all togheter and 
"merge" the two functions by hand:

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

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

def merge(f1,f2):
    s1=inspect.getsource(f1).splitlines()[1:]
    s2=inspect.getsource(f2).splitlines()[1:]
    lines=['def mergedfunction():\n']
    for line1,line2 in zip(s1,s2):
        lines.append(line1+'\n')
        lines.append(line2+'\n')
    dic={}; exec ''.join(lines) in dic
    return dic['mergedfunction']

f=merge(f1,f2)
f()
 
Output:
1-1
2-1
1-2
2-2
1-3
3-3

Exercise left for the reader: show the pittfalls of this approach.


               Michele




More information about the Python-list mailing list