Closures
- VC Healy
- Jul 26, 2020
- 2 min read
A nested scope/function is where a function is held within another function. The inner function could be making use of free variables in the outer function as part of its routine.
def main_function():
msg = 'Hello' # Free Variable
def inner_function():
print (msg) # Request for Free Variable
inner_function()
print (msg)
main_function()
The order that the commands are inside a function matters.
In the following, the msg variable can be seen in two locales.
The main_function and the inner_function.
msg of the inner_function is not seen by the main_function. The inner_function msg is a local variable. When it goes to print, the inner variable is assigned the value of the free variable and the inner_function does not look outside the main_function.
The first print in this function will be actioned by the inner_function() and the main_function print statement will action after
def main_function():
msg = 'Vincent'
def inner_function():
msg = 'Hello'
print (msg)
inner_function()
print(msg)
main_function()
The following code shows another possible way of changing one of the variables.
msg is initial given the value 'Vincent' as the main_function starts. As it progresses into the inner_function, the non-local msg commands then states that msg is a variable outside of the function. This means when the variable msg is changed to 'Hello' by the inner_function it changes the value outside the inner function as well.
Both the main_function and the inner_function will print the same value of 'Hello'
def main_function():
msg = 'Vincent'
def inner_function():
nonlocal msg
msg = 'Hello'
print (msg)
inner_function()
print(msg)
main_function()
Instead of the function printing out values to the console the inner_function is returning a callable value to the main_function. The main_function that is callable is then assigned to a variable object. This allows the variable to be treated as the main_function.
def main_function():
msg = 'Mars Attacks'
def inner_function():
print (msg)
return inner_function
object = main_function()
Adding the parenthesis to the object will action the main_function and print the msg.
object()
Mars Attacks
Comments