0

As you can guess by the title I'm not quite sure how to ask this question. Anyway the problem is the following:

I want to pass a numpy array as a parameter to a function, inside this function I want to make a copy of that array, then pass the array to another function manipulating the array and in the end replace the array with the copy.

...
arr = np.array([...])
arr_ocp = arr.copy()
func1(arr)
print np.array_equal(arr,arr_ocp) -> False
...

def func1(arr):
  arr_cp = arr.copy()
  func2(arr)
  print np.array_equal(arr,arr_cp) -> False
  arr = arr_cp
  print np.array_equal(arr,arr_cp) -> True

def func2(arr):
  ...
  arr[x:x+l,y:y+w] += np.array(...)
  ...

Now i did a few prints and it turns out that in func1 arr is the same at the beginning and the end, which I'd have expected.But if I do a print after func1(arr), arr is now the value of arr after func2. So why do the manipulations of func2 apply to arr but not the arr = arr_cp?

In hindsight it's probably better to pass the copy to func2 instead of the array itself, still I'd not expect this to happen like this. Am I missing something here?

4
  • 2
    can you explicit the positions of the prints with the actual output? Commented Apr 6, 2016 at 12:41
  • 1
    Added a lot more but those are probably the most important Commented Apr 6, 2016 at 12:44
  • 1
    can you include the code for func2 as well? Commented Apr 6, 2016 at 12:44
  • 1
    also the output of the prints, so I can understand the problem Commented Apr 6, 2016 at 12:46

1 Answer 1

4

You need to understand the difference between mutating and rebinding. When you do arr = arr_cp, all you're doing is rebinding the name arr to whatever is referred to by arr_cp. You don't in any way affect the object that was previously bound to arr.

However, when you do anything to arr itself - for example, arr[0] = 'foo' - that is a mutation, and changes the actual object. All names that are bound to that same object will continue to do so, so the changes will be visible to them all.

Sign up to request clarification or add additional context in comments.

1 Comment

After having been alerted to this years later due to serial downvoting, I still find it interesting. Because it's not trivial, I first thought it would be about shadowing and that manipulating the parameter variable (by rebinding it to something else or changing it) would trigger a global change. But it's really because I manipulate the underlying object that the global changes are preserved while the mere rebinding is caught by shadowing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.