creating generators from function
simonwittber at gmail.com
Wed Dec 8 10:13:16 CET 2004
I use a coroutine/generator framework for simulating concurrent processes.
To do this, I write all my functions using the general form:
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
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?
from opcode import opmap
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,
print types.GeneratorType(f)(codeobj, f.func_globals, f.func_name,
More information about the Python-list