global and nonlocal

Let a function change variables from the global scope or from an enclosing function.

On this page

Example

#
Python
def make_counter():
    count = 0
    def increment():
        nonlocal count
        count += 1
        return count
    return increment

counter = make_counter()
counter()
counter()
print(counter())

total = 0
def add_points(points):
    global total
    total += points

add_points(20)
add_points(30)
print(total)
Resultsaved result, you can check it
3
50

Definition and usage

#

A variable assigned inside a function is local by default. If you want to change a variable defined outside the function, you have to declare it: global for module-level variables, nonlocal for variables of an enclosing function.

nonlocal is useful in nested functions, for example when creating a counter that remembers its state between calls, a so-called closure.

Overusing global makes it hard to track who changes data and when. It is usually better to pass the value as an argument and return a new one with return, or use a class.

Syntax

#
Syntax
def function():
    global variable
    variable = new_value

Good practices

#
  • Before using global, check whether returning the value from the function is not enough.
  • Simply reading a global variable does not require global. The declaration is only needed for assignment.

Related entries

#

Spotted a mistake or missing an example? Write to us.