We covered a number of examples using scope. I have decided to post these examples so that they will hopefully help you all better understand scope.
Scope Example 1: Variables passed through function definitions
In the example above, when we call foo(x)
, we pass the function foo(n)
a copy of the
value of variable x
from the main scope. This is now treated as a new variable n
within
foo(n)
, so when we change its value, it does not modify the value of x
Scope Example 2: Internal variable has same name as external variable
If you look at the example above, you might expect the last print x
to display qwerty.
This is not the case, as the x variable inside foo and outside foo have different scopes,
and are treated independently.
Scope Example 3: Accessing a variable from parent scope
In this example, the function foo()
, when we try to access the variable x
, the program
recognizes that we never set x
from within the scope of foo()
, so it will look for x
in the parent scope, find that variable x
and print its value.
Scope Example 4: Setting a variable from the parent scope
In the above example, we will get the error
UnboundLocalError: local variable 'x' referenced before assignment
The reason for this is because we are setting the value of the variable x
inside foo()
the program will try to resolve the value of the variable x
within the scope of foo()
.
As it hasn’t been set yet, the program is unable to do this.
Scope Example 5: Accessing variables in the global scope
In the above example, the foo()
states explicitly that when we refer to the variable
x
, we mean the variable x
from the global scope. So when we first print x
in foo()
we have the value of 123
from the parent scope. When we set x
in foo()
, we update
the value in the parent scope, so that when we print x
at the end, it’s now 456
there
as well.
Scope Example 6: Accessing the global scope, continued
The above example is very similar to Example 5, but we set the variable x
from the
foo()
function before accessing in the global scope.