def bind_partial(self, *args, **kwds):
"""
Binds the provided positional and keyword arguments
and returns a new ``Function`` object with an updated signature.
"""
# We only need the signature, so clean the function body before eval'ing.
empty_func = self.replace(tree=replace_fields(self.tree, body=[ast.Pass()]))
signature = inspect.signature(empty_func.eval())
bargs = signature.bind_partial(*args, **kwds)
# Remove the bound arguments from the function AST
bound_argnames = set(bargs.arguments.keys())
new_tree = filter_function_def(self.tree, bound_argnames)
# Add assignments for bound parameters
assignments = []
gen_sym = GenSym.for_tree(new_tree)
new_bindings = {}
for name, value in bargs.arguments.items():
node, gen_sym, binding = reify_unwrapped(value, gen_sym)
new_bindings.update(binding)
assignments.append(ast.Assign(
targets=[ast.Name(id=name, ctx=ast.Store())],
value=node))
new_globals = dict(self.globals)
new_globals.update(new_bindings)
new_tree = replace_fields(new_tree, body=assignments + new_tree.body)
return Function(new_tree, new_globals, self.closure_vals, self._compiler_flags)
评论列表
文章目录