PythonSyntax and keywords
global and nonlocal
Let a function change variables from the global scope or from an enclosing function.
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_valueGood 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
#- defDefines a function: a named block of code with parameters that you can call multiple times.
- classDefines a class: a template for objects that combines data with the functions that act on it.
- lambdaA short anonymous function written as a single expression.
- DecoratorsFunctions that wrap other functions and add behavior to them, such as logging or permission checks. Written as @name.
Spotted a mistake or missing an example? Write to us.