Python Global, Local and Non-local Variables
We see the difference between global, local, and nonlocal variables of functions.
Global Variables
A Python global variable is declared outside the function or in the global scope.
This means that a global variable can be accessed inside or outside functions.
For example:
x = "global string"
def my_function():
print("x inside:", x) # x inside: global string
my_function()
print("x outside:", x) # x outside: global string
If you want to change the value of a global variable within a function, you must use the global
keyword. Otherwise, an UnboundLocalError
error is raised.
x = "global string"
def my_function():
x = x + " append something"
print("x inside:", x)
my_function()
# UnboundLocalError: local variable 'x' referenced before assignment
Visit Python Global Keyword to learn more.
Local Variables
A Python local variable is declared inside the function's body or in the local scope.
For example, a variable declared inside a function is a local variable:
def my_function():
y = "local"
print(y)
foo()
Output
local
Local variables can't be accessed from outside the scope in which they are defined.
def my_function():
y = "local"
my_function()
print(y)
# NameError: name 'y' is not defined
Non-local Variables
Nonlocal variables are used in nested functions whose local scope is not defined.
This means that the variable can't be in either the local or global scope.
The nonlocal
keyword is used to create nonlocal variables.
For example, use the nonlocal
keyword to create a nonlocal variable:
def outer_function():
x = "local"
def inner_function():
nonlocal x # nonlocal declaration
x = "nonlocal"
print("inner:", x)
inner_function()
print("outer:", x)
outer_function()
Output:
inner: nonlocal
outer: nonlocal
Changes in the value of a nonlocal variable are reflected in the local variable.
Examples
Global and Local variables in the same code
Global and local variables can be used in the same code.
If the global variable is to be modified, it must be declared within the local scope with the global
keyword.
In the following example, x
is a global variable and y
is a local variable:
x = "global "
def foo():
global x
y = "local"
x = x * 2
print(x)
print(y)
foo()
Global variable and Local variable with same name
The name x
is used for both the global and the local variable. You get a different result when printing the same variable, because the variable is declared in both scopes (local scope inside my_function()
and global scope outside my_function()
).
x = 5
def my_function():
x = 10
print("local x:", x)
my_function()
print("global x:", x)
Output
local x: 10
global x: 5