How can I dynamically execute function in current scope and add it as property of the calling function?
问题 I have some code like this: def f1(): <some stuff here> . . . @mylib.codegen def f2(args): f1() <some more stuff here> mylib.py : def codegen(fn): src = inspect.getsource(fn) original_ast = ast.parse(src) new_ast = transform_ast(original_ast) code_obj = compile(new_ast, '<auto-generated>', 'exec') myscope = {} exec code_obj in myscope fn.generated_fn = myscope['name'] # Where name is the binding created by execing code_obj To summarize, mylib.codegen is a decorator which parses code of f,