0

I just came across what I find very strange behaviour that I would like to understand. Unfortunately I don't really know how to search for it.

If I have a function

def func(A, B):
    A_ = A
    A_[0, 1] = A_[0, 1] + 1

and a dictionary

dicto = {"A": np.zeros((3,3))} .

Now calling the function with func(dicto["A"]) will cause the array stored in the dictionary dicto to be changed. This is similar to a pointer, but I thought pointers don't exist in Python?

Why is that the case? I would expect A_ to be a local variable, meaning any change applied to it shouldn't affect the variable stored in the dictionary.

This behaviour changes to what I expected when the function is changed to

def func(A, B):
    A_ = A * 1
    A_[0, 1] = A_[0, 1] + 1 .

How can I achieve what I want without the extra calculation of A * 1?

  • You want a deep copy of your object, am I right? – Jack Lilhammers Feb 28 '21 at 19:15
  • I'm not sure if I understood correctly what a deep copy is. I want to create a copy of the original, change an entry in that matrix, use it for a calculation and then discard it again afterwards. What would be the best way to do that? How can I avoid passing by reference? – LondonLiliput Feb 28 '21 at 19:24
  • You can't. Objects in Python are passed by reference – Jack Lilhammers Feb 28 '21 at 19:26
  • Just as an update, I found a numpy function that does this for me: https://numpy.org/doc/stable/reference/generated/numpy.copy.html – LondonLiliput Feb 28 '21 at 22:37
  • It's however a lot slower: %timeit z = x*1 931 ns ± 7.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) | %timeit z = np.copy(x) 2.26 µs ± 40.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) – LondonLiliput Feb 28 '21 at 22:40

0 Answers0