如何在 Python 中对函数进行深度复制?

2022-01-20 00:00:00 python function 复制 deep-copy

问题描述

我想在 Python 中制作一个函数的深拷贝.copy 模块没有帮助,根据 documentation,其中说:

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"""

相关文章