I thought that changes to variables passed to a python function remain in the function’s local scope and are not passed to global scope. But when I wrote a test script:
#! /usr/bin/python
from numpy import *
def fun(box, var):
box[0]=box[0]*4
var=var*4
return 0
ubox,x = array([1.]), 1.
print ubox,x
fun(ubox,x)
print ubox,x
The output is:
[myplay4]$ ./temp.py
[ 1.] 1.0
[ 4.] 1.0
The integer variable x is not affected by the operation inside the function but the array is. Lists are also affected but this only happens if operating on list/array slices not on individual elements.
Can anyone please explain why the local scope passes to global scope in this case?
The important thing to realize is that when pass an object to a function, the function does not work with an independent copy of that object, it works with the same object. So any changes to the object are visible to the outside.
You say that changes to local variables remain local. That’s true, but it only applies to changing variables (i.e. reassigning them). It does not apply to mutating an object that a variable points to.
In your example, you reassign
var, so the change is not visible on the outside. However you’re mutatingbox(by reassigning one of its elements). That change is visible on the outside. If you simply reassignedboxto refer to a different object (box = something), that change would not be visible on the outside.