If a variable is used as an argument of a function, then all modifications done inside the function with the argument apply to the variable. This is normal and expected, but in many cases undesirable. What is the best practice to prevent this behaviour? Example:
import numpy as np
def func(A):
for ind in range(A.shape[0]):
A[ind] = A[ind]+1
return A
A = np.array([1, 2, 3])
NewA = func(A)
print(A)
print(NewA)
Out: [2, 3, 4]
Out: [2, 3, 4]
While we want:
Out: [1, 2, 3]
Out: [2, 3, 4]
So far I came up only with two ideas.
Method one: obviously, pass a copy of a variable:
A = np.array([1, 2, 3])
NewA = func(A.copy())
print(A)
print(NewA)
Out: [1, 2, 3]
Out: [2, 3, 4]
Returns what expected but becomes really annoying when one have a function of 5 arguments: it is just too long to type .copy() every time.
Method two: Modify the function body
def func(A):
B = A.copy()
for ind in range(B.shape[0]):
B[ind] = B[ind]+1
return B
This is equally annoying and requires modification of functions. Any other ideas?