如何在Python中对函数进行深层复制? [英] How can I make a deepcopy of a function in Python?

查看:117
本文介绍了如何在Python中对函数进行深层复制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Python中做一个函数的deepcopy。根据文档 模块无用, p>

I would like to make a deepcopy of a function in Python. The copy module is not helpful, according to the documentation, which says:


此模块不会复制像模块,方法,堆栈跟踪,堆栈框架,文件,
socket,window,array,任何类似的类型。它通过返回原始对象不改变复制函数和类(浅
和深)这与
这些被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.

我的目标是有两个函数相同的实现,但使用不同的docstrings。

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

那么该如何做呢?

推荐答案

FunctionType构造函数用于创建函数的深层副本。 / p>

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

这篇关于如何在Python中对函数进行深层复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆