I have the following problem. I have a function which takes 2 lists as arguments. In order not to mutate any of them I would like to use the copy module and create a deepcopy of both.
Up to now I have only come this far:
import copy
def f(a1, a2):
a1 = copy.deepcopy(a1)
a2 = copy.deepcopy(a2)
# Rest of function code below.
I personally do not think that this code looks nice. It would be better to have something like this
import copy
def f(a1, a2):
newdeepcopy(locals())
# Rest of function code below. The same code as above.
The function newdeepcopy should take locals as an argument and redefine the the variables a1 and a2 only in the scope of f. Is this possible?
How about using a decorator?
def deep_copy_params(to_call):
def f(*args, **kwargs):
return to_call(*copy.deepcopy(args), **copy.deepcopy(kwargs))
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With