Deepcopy所有函数参数

时间:2018-03-29 23:52:01

标签: python python-3.x function copy

我有以下问题。我有一个函数,它将2个列表作为参数。为了不改变它们中的任何一个,我想使用copy模块并创建两者的deepcopy

到目前为止,我只走到这一步:

import copy 

def f(a1, a2):
    a1 = copy.deepcopy(a1)
    a2 = copy.deepcopy(a2)
    # Rest of function code below.

我个人认为这段代码看起来不太好。有这样的东西会更好

import copy 

def f(a1, a2):
    newdeepcopy(locals())
    # Rest of function code below. The same code as above.

函数newdeepcopy应该将locals作为参数,并仅在f的范围内重新定义变量a1和a2。这可能吗?

1 个答案:

答案 0 :(得分:4)

如何使用装饰器?

代码:

def deep_copy_params(to_call):
    def f(*args, **kwargs):
        return to_call(*(copy.deepcopy(x) for x in args),
                       **{k: copy.deepcopy(v) for k, v in kwargs.items()})
    return f

测试代码:

import copy

@deep_copy_params
def test(a, b, c=0):
    print(a, b, c)
    a[1] = 3
    b[2] = 4
    c[3] = 5
    print(a, b, c)

aa = {1: 2}
bb = {2: 3}
cc = {3: 4}

test(aa, bb, cc)
print(aa, bb, cc)

结果:

{1: 2} {2: 3} {3: 4}
{1: 3} {2: 4} {3: 5}
{1: 2} {2: 3} {3: 4}