如何在 Python 中制作函数的深层副本?
我想在 Python 中制作一个函数的深层副本.根据文档,copy 模块没有帮助,其中说:
I would like to make a deepcopy of a function in Python. The copy module is not helpful, according to the documentation, which says:
此模块不复制模块、方法、堆栈跟踪、堆栈帧、文件等类型,套接字、窗口、数组或任何类似的类型.它会复制"函数和类(浅和深度),通过返回原始对象不变;这与方式兼容这些由 pickle 模块处理.
This module does not copy types like module, method, stack trace, stack frame, file, socket, window, array, or any similar types. It does "copy" functions and classes (shallow and deeply), by returning the original object unchanged; this is compatible with the way these are treated by the pickle module.
我的目标是拥有两个具有相同实现但具有不同文档字符串的函数.
My goal is to have two functions with the same implementation but with different docstrings.
def A():
"""A"""
pass
B = make_a_deepcopy_of(A)
B.__doc__ = """B"""
那么如何才能做到这一点?
So how can this be done?
FunctionType 构造函数用于制作函数的深层副本.
The FunctionType constructor is used to make a deep copy of a function.
import types
def copy_func(f, name=None):
return types.FunctionType(f.func_code, f.func_globals, name or f.func_name,
f.func_defaults, f.func_closure)
def A():
"""A"""
pass
B = copy_func(A, "B")
B.__doc__ = """B"""