0

I use python3.9 where I declared a variable x, which is an input to function output = model(x). After the call x gets the same values as output variable. I expected that x before and after call should be the same, but it is not. The code behaves as if the output variable and local variables in the function model are pointers to x. Could you kindly explain this behavior? I've never met anything like that in Fortran, C/C++ and Matlab. Here is an example of my python code

import numpy as np

def model(aux):
    for i in range(0,len(aux)):
        aux[i] = np.sin( aux[i] ) + 1
    return aux

length = 5

x =  np.linspace(0,1,length)

print(' X variable  BEFORE the function call ')
print(x)

output = model(x)

print(' X variable  AFTER the function call ')
print(x)

print(' Output variable  AFTER the function call ')
print(output)

Ad here is what I get:

 X variable  BEFORE the function call 
[0.   0.25 0.5  0.75 1.  ]
 X variable  AFTER the function call 
[1.         1.24740396 1.47942554 1.68163876 1.84147098]
 Output variable  AFTER the function call 
[1.         1.24740396 1.47942554 1.68163876 1.84147098]

Shouldn't X variable BEFORE and AFTER be the same?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 4
    This is a good guide on variable behavior in Python: https://nedbatchelder.com/text/names.html – Michael Cao Feb 07 '23 at 19:32
  • 1
    I'm not a numpy users... but if you know 'c' then it might be best to thinking of "x" as a pointer to your array. The parameter "aux" is pointing to the same memory space. So when you modify "aux" ... you would see the same updates in "x". If you want aux to create a copy of the object, you would need to explicitly make a new object and copy the values. – RobertB Feb 07 '23 at 19:33
  • 1
    Out of interest, isn't pass-by-reference the standard in Fortran, so that Fortran would behave similarly to Python in cases like this? For example https://stackoverflow.com/questions/38848530/passing-arguments-by-value-in-fortran-95 – slothrop Feb 07 '23 at 19:35
  • 1
    Since you mention C++, Python pass-by-assignment semantics are exactly like passing around `T*`s (or perhaps more aptly `std::shared_ptr`s) in C++. – Brian61354270 Feb 07 '23 at 19:36
  • 1
    Use `aux.copy()` before the loop assignment if you don't want this behavior. – Ícaro Lorran Feb 07 '23 at 19:53

0 Answers0