Search code examples
pythonglobal-variables

Difference behavior between a python global variable and a global list?


I am confused with the python's design of global variables, it seems quite different for a normal global variable and a global list, consider the following code:

global_list = []
global_var = 0


def foo():
    for i in range(10):
        global global_var  # without this, error occurs
        global_var += 1
        global global_list  # without this, fine!
        global_list.append(i)


foo()
print(global_list)
print(global_var)

The code is quite self-explained, I would like to know why this is the case, what is the logic behind that. Besides, I've also tested a dictionary, it behaves like a list. What about other stuff, such as a class instance or something...


Solution

  • From the Programming FAQs:

    In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

    When you write:

    global_var += 1
    

    You are assigning a value to the name global_var after you have already referenced the global version The += construct needs to read the global then reassign to it — it's equivalent to:

    global_var = global_var + 1
    ^            ^
    |            |--global reference
    |- local assignment
    

    According to the above rule, this would make it a local variable unless declared global but you've already referenced the global.

    When you write:

    global_list.append(i)
    

    You are not assigning a new value to the name global_list. global_list still points to the same array, the same thing happens with a dictionary. You would need to declare global global_list if you tried to reassign with something like:

    global_list = global_list + [i]