creating generators from function

Simon Wittber simonwittber at gmail.com
Wed Dec 8 04:13:16 EST 2004


I use a coroutine/generator framework for simulating concurrent processes.

To do this, I write all my functions using the general form:

while True:
    do stuff
    yield None

To make these generator functions compatible with a standard thread
interface, I attempted to write a decorator which converts a standard
function into a generator function (code attached below).
Unfortunately, I received an exception, before I could test if my idea
would work:

TypeError: cannot create 'generator' instances

I guess I can go the other way, and convert a generator into a
function, but that just doesn't seem right.

Is there anyway solve the problem described?

Sw.


from opcode import opmap
import types
globals().update(opmap)

def generatorize(f):
    co = f.func_code
    nc = [ord(x) for x in co.co_code]
    for op,i in enumerate(nc):
        if op == RETURN_VALUE:
            nc[i] = YIELD_VALUE
    newcode = ''.join([chr(x) for x in nc])
    codeobj = type(co)(co.co_argcount, co.co_nlocals, co.co_stacksize,
                        co.co_flags, newcode, co.co_consts, co.co_names,
                        co.co_varnames, co.co_filename, co.co_name,
                        co.co_firstlineno, co.co_lnotab, co.co_freevars,
                        co.co_cellvars)
    
    print types.GeneratorType(f)(codeobj, f.func_globals, f.func_name,
f.func_defaults, f.func_closure)
    return f

@generatorize
def f():
    while True:
        return 1
        
def g():
    while True:
        yield 1

print g()
print f()



More information about the Python-list mailing list