我有以下问题。我有一个函数,它接受两个列表作为参数。为了不使它们发生变异,我想使用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应该将局部变量作为参数,并仅在f的范围内重新定义变量a1和a2。这可能吗?

最佳答案

用个装饰工怎么样?
代码:

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}

10-06 10:35