def eval_function_def(function_def, globals_=None, flags=None):
"""
Evaluates an AST of a function definition with an optional dictionary of globals.
Returns a callable function (a ``types.FunctionType`` object).
"""
assert type(function_def) == ast.FunctionDef
# Making a copy before mutating
module = ast.Module(body=[copy.deepcopy(function_def)])
ast.fix_missing_locations(module)
if flags is not None:
kwds = dict(dont_inherit=True, flags=flags)
else:
kwds = {}
code_object = compile(module, '<nofile>', 'exec', **kwds)
locals_ = {}
eval(code_object, globals_, locals_)
return locals_[function_def.name]
评论列表
文章目录