0

I am not clear about global variables declared within functions in python. I can understand the basic of global versus local variables, and can follow most of the online examples that demonstrate the concepts. However, I cannot find any solutions to help me out of the situation I came across.

see a simple code snippet below:

import numpy as np

def fun1(month_list):
    
    #global cc
    #global aa
    #global dd
    print(aa)
    
    for ii in range(2):
        for jj in range(3):
            aa[ii,jj] = month_list *2 + bb[ii,jj]
            bb[ii,jj] = 2
    dd = 1
            
    cc = aa
    print(aa)
    return
    
def fun2():
    
    global aa
    global bb
    global dd
    
    aa = np.zeros((2,3))
    bb = np.ones((2,3))
    dd = 2
    
    return

fun2()
fun1(3)
print(aa)
print(bb)
print(dd)

it seems that without declaring "aa" and "bb" as global variables in fun1, we can still change the values of aa and bb within fun1 after calling fun2 and print the modified "aa" and "bb" outside fun1. However, without declaring "dd" as a global variable in fun1, "dd" remains a local variable in fun1.

Any hints why we must declare "dd" as a global variable within fun1 in order to modify its value while it is unnecessary to do so for array variables "aa" and "bb"?

Thanks a lot, Lin

Lin Lin
  • 25
  • 4

1 Answers1

0

This has to do with the concept of memory references, mutability and shadowing. When you declare an array, you are creating a variable that holds a reference to the array. That is what is global in fun2(). When you operate on the arrays in fun1(), you are operating on the global reference and interacting with the data the array holds, but the reference to the array stays the same.

However for your dd case when you do the following line:

dd = 1

in fun1(), you are 'shadowing' the global variable dd, so you are not operating on it.

In fact, since numbers are immutable there is no real way to change them in place like an array since they are immutable vs the mutable array.

And we are not shadowing the array variables because we are not redeclaring them with an '=' statement, so we inherit them from the global scope.

See the following blog post for more information on mutable vs immutable data. https://medium.datadriveninvestor.com/mutable-and-immutable-python-2093deeac8d9

Also, see similar but different stack overflow for more additional details. Confusing variable scope (shadowing variable from outer scope)

nklisch
  • 76
  • 3