Learning Resources
 

Using global and nonlocal statement


Using The global Statement

If you want to assign a value to a name defined at the top level of the program (i.e. not inside any kind of scope such as functions or classes), then you have to tell Python that the name is not local, but it is global. We do this using the global statement. It is impossible to assign a value to a variable defined outside a function without the global statement.

You can use the values of such variables defined outside the function (assuming there is no variable with the same name within the function). However, this is not encouraged and should be avoided since it becomes unclear to the reader of the program as to where that variable's definition is. Using the global statement makes it amply clear that the variable is defined in an outermost block.

Example:

#!/usr/bin/python
# Filename: func_global.py
 
x = 50
 
def func():
    global x
 
    print('x is', x)
    x = 2
    print('Changed global x to', x)
 
func()
print('Value of x is', x)

Output:

   $ python func_global.py
   x is 50
   Changed global x to 2
   Value of x is 2

How It Works:

The global statement is used to declare that x is a global variable - hence, when we assign a value to x inside the function, that change is reflected when we use the value of x in the main block.

You can specify more than one global variable using the same global statement e.g. global x, y, z.

Using nonlocal statement

We have seen how to access variables in the local and global scope above. There is another kind of scope called "nonlocal" scope which is in-between these two types of scopes. Nonlocal scopes are observed when you define functions inside functions.

Since everything in Python is just executable code, you can define functions anywhere.

Let's take an example:

#!/usr/bin/python
# Filename: func_nonlocal.py
 
def func_outer():
    x = 2
    print('x is', x)
 
    def func_inner():
        nonlocal x
        x = 5
 
    func_inner()
    print('Changed local x to', x)
 
func_outer()

Output:

   $ python func_nonlocal.py
   x is 2
   Changed local x to 5

How It Works:

When we are inside func_inner, the variable x defined in the first line of func_outer is neither in the local scope (the variable definition is not part of func_inner's block) nor in the global scope (it is not in the main block either). We declare that we want to access this specific x by using nonlocal x.

Try changing nonlocal x to global x, then remove the whole statement, observing the difference in behavior in these two cases.

-Swaroopch