Python Global, Local and Nonlocal Variables
In Python, a local variable is defined inside a function and a global variable is defined outside of a function. Global variables are available inside functions and can be overridden by redefining its value inside a function whereas locally defined variables will only be available inside the function.
In this tutorial, we will learn how to use global, local and nonlocal variables in Python with examples.
To create a global variable we will assign a value to a variable outside of a function. This variable can be used anywhere in the program, including within functions and functions inside classes.
g = 'hello' def hello(): print('inside a function:', g) class something: def foo(self): print('inside a class:', g) hello() p1 = something() p1.foo() print('outside:', g)
inside a function: hello inside a class: hello outside: hello
In the example above the variable
g was available in the function
hello() and in the function
foo() inside the
Local variables are only available inside a function. They can be defined inside a function or the value of a global variable can be changed inside a function and the global variable will not be modified. Let's see how this works.
def hello(): l = 'hello' print(l) hello() print(l)
hello --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-13-5cca54e0f7db> in <module> 4 5 hello() ----> 6 print(l) NameError: name 'l' is not defined
In the example above we tried to use the variable
l in the global scope, which was only defined inside the function
hello() so an undefined variable exception was thrown.
Here is another example demonstrating how a global variable can be changed locally without affecting the value of the global variable.
l = 'hello' def hello(): l = 'goodbye' print(l) hello() print(l)
It is possible to change the value of a variable inside a nested function for the parent scope. This is done by using the nonlocal keyword before the variable name. Then its value can be changed and it will also be changed in the scope of its parent.
def outer(): g = "local" def inner(): nonlocal g g = "nonlocal" print("inner:", g) inner() print("outside of inner:", g) outer()
inner: nonlocal outside of inner: nonlocal
You now know how variable scopes work in Python. Global variables can be used anywhere and local variables are only available inside the function unless the nonlocal keyword is applied to them.