def mess_control(f, *, debug=0):
assert inspect.isfunction(f)
members = dict(inspect.getmembers(f))
global_dict = members["__globals__"]
source_filename = inspect.getsourcefile(f)
f_ast = ast.parse(inspect.getsource(f))
_, starting_line = inspect.getsourcelines(f)
# ast_demo.increment_lineno(f_ast, starting_line - 1)
if debug:
print("AST:", ast.dump(f_ast))
visitor = ControlMess()
new_ast = visitor.visit(f_ast)
if debug:
print('NEW AST:', ast.dump(new_ast))
ast.fix_missing_locations(new_ast)
co = compile(new_ast, '<ast_demo>', 'exec')
fake_locals = {}
# exec will define the new function into fake_locals scope
# this is to avoid conflict with vars in the real locals()
# https://stackoverflow.com/questions/24733831/using-a-function-defined-in-an-execed-string-in-python-3
exec(co, None, fake_locals)
# new_f = locals()[visitor._new_func_name(f.__name__)]
return fake_locals[f.__name__]
评论列表
文章目录