March 2019, Reading time: 2 minutes
In this post I will explain the difference between the various scopes in python. By scope we mean that each variable, depending on where it is defined, has a certain area where it is valid and as a concequence has also a certain lifetime.
Lets start with an example
a=1 def func(): a=2 print(a) func() print(a)
We have two variables called “a”, one is defined outside of anything and we say it has a module or global scope and the other one is defined inside a function and it has a local scope. The two variables are different. The local variable a exists only for the duration of function func, while the global exists for the execution of the whole program.
The output is
We can change the value of global a if we want, by doing this
a = 1 def func(): global a a = 2 print(a) func() print(a)
Here we say that the value a in func is the global a, so it can be changed. The outcome is
Lets see the following. What will happen in the following code?
a = 1 def func(): print(a) a = 2 func() print(a)
You may have expected to print 2 1, but the above code will give an error: UnboundLocalError: local variable ‘a’ referenced before assignment. From the moment you have assignment, python considers it a local variable.
Now lets look at the following:
a = 1 def func(): print(a) func()
The output will be 1. Because func has no local variable, it will access its enclosing scope which in this case is the global scope. But look at the following:
a = 1 def func1(): a = 2 def func2(): print(a) func2() func1()
What is the output? In this case the enclosing scope of func2 is func1 so it will print 2.
If you want the change the enclosing variable you have to declare it nonlocal. Example
a = 1 def func1(): a = 2 print(a) def func2(): nonlocal a a=3 print(a) func2() print(a) func1() print(a)
The output will be: scroll down
2 3 3 1
first our program calls func1, func1 prints 2
then func1 calls func2, func2 changes a to 3 and prints 3
func2 finishes and now we have the print after func1, this will print also 3
finally we have the print outside the function. this will print 1