Variable Tips

Learn how local and global variables play an important role with respect to safety in Python code.

Understand local variables

Many things are confusing in Python, but few are as confusing as local and global variables. The scope of a local variable is restricted to the enclosing function but the scope of a global variable isn’t. What makes a variable local or global?

A variable is local in a function if it’s declared inside it, unless explicitly marked as global in the same function. Because the only way to declare a variable in Python is to use it on the left-hand side (LHS) of an assignment statement, Python variables are always initialized. Whether or not a variable in a function is global, doesn’t depend on whether a global variable with the same identifier already exists. If it does, the function may have a local variable with the same name that will shadow the global variable, making it invisible in the function.

Let gv = 1 be a global variable. The variable remains global in the following two functions.

  • f1() treats gv as a global because it is marked as global, despite the assignment statement.

  • f2() treats gv as a global because there is no assignment statement.

Let’s try the code below.

Press + to interact
def f1():
global gv
gv+=1
return gv
print(f1(),gv)
def f2():
return gv + 1
print(f2(), gv)

The gv variable in the third example given below is local because of the augmented assignment statement. It attempts to shadow the namesake of the global variable. However, it’s unsuccessful because an augmented assignment doesn’t create a new variable.

Let’s run the code below and observe:

Press + to interact
def f3():
gv +=1
return gv
print(f3(),gv)

The fourth function is shown below. It successfully creates the local variable, which has the same name identifier as the global variable, ...