I am having trouble understanding how python handles storage and retrieval of variables inside functions. In the following code, I initialize the variable 'gg' as being equal to one of the many arrays that I pass to the function. I then update the variable with some operations. Finally I have the variable returned to the base space. The problem is that the function seems to forget all the changes I have performed on the variable.
Here is an example:
XX = {hh:np.random.rand(5) for hh in np.arange(4)}
def ffun(data_in, vols = None):
count = 0
for voli, vol in enumerate(vols):
if count==0:
gg = data_in[vol]
else:
gg += data_in[vol]+0
count += 1
print([voli,vol,count,max(gg)])
print([gg[:3]])
# gg /= count+1
print(count)
print([voli,vol,count,max(gg)])
print([gg[:3]])
return gg
HH = ffun(XX,vols=np.arange(4))
HH==XX[0]
It seems as though this is some issue with internal pointers to variables stored in memory. If I initialize 'gg' with either <gg = data_in[vol] + 0> or <gg = data_in[vol].copy()>, then everything works. Everything also works if I move the operations to the base space, as in:
XX = {hh:np.random.rand(5) for hh in np.arange(4)}
data_in=XX
vols = np.arange(4)
count = 0
for voli, vol in enumerate(vols):
if count==0:
gg = data_in[vol]
else:
gg += data_in[vol]+0
count += 1
print([voli,vol,count,max(gg)])
print([gg[:3]])
# gg /= count+1
print(count)
print([voli,vol,count,max(gg)])
print([gg[:3]])
HH==XX[0]
What am I missing? Why does gg revert to its initial value? And why does this only happen to the returned value? the variable is clearly changing within the function call.