Correct Use Of Global Variables In Python 3 Correct Use Of Global Variables In Python 3 python python

Correct Use Of Global Variables In Python 3


In the first case the global keyword is pointless, so that is not correct. Defining a variable on the module level makes it a global variable, you don't need the global keyword.

The second example is correct usage.

However, the most common usage for global variables are without using the global keyword anywhere. The global keyword is needed only if you want to reassign the global variables in the function/method.


You need to use the global keyword in a function if you use the global variable in a way that would otherwise be interpreted as an assignment to a local variable. Without the global keyword, you will create a local variable that hides the global in the scope of the function.

Here are a few examples:

global_var = 1def example1():    # global keyword is not needed, local_var will be set to 1.    local_var = global_vardef example2():    # global keyword is needed, if you want to set global_var,    # otherwise you will create a local variable.    global_var = 2def example3():    # Without using the global keyword, this is an error.    # It's an attempt to reference a local variable that has not been declared.    global_var += 1


"in a way that would otherwise be interpreted as an assignment to a local variable" --- yes, but here is a subtle detail:

------------------- error: local variable 'c' referenced before assignment

def work():  c += 3c = 0work()print(c)

------------------- error: local variable 'c' referenced before assignment

c = 0def work():  c += 3work()print(c)

------------------- prints [3]

def work():  c.append(3)c = []work()print(c)

------------------- prints [3]

c = []def work():  c.append(3)work()print(c)