How and What are Closures
- VC Healy
- May 23, 2020
- 2 min read
Updated: May 24, 2020
#Closure 1
def outer_func():
message = 'Hi' #Variable set in the outer func
def inner_func():
print(message)
# message variable is not in the inner func, the func looks for a
#free variable in the next level up
return inner_func()
# outfunc()
my_func= outer_func
# name the users function my_func to reference the outer func
# of the closure
#(making the closure available to a variety of functions)
my_func()
# Adding the parenthesis converts the my_func function from a
# variable holding
# a function to a function that is calling the outer function
Showing the initial nested function. The inner function doesn't have a local variable so it looks for a free variable on the next level up.
# Closure 2
# Following on from Closure 1 showing the closure being used for two variable
#labelled functions
#
# Note the inner function is pulling the msg value from the outer argument,
# the argument is taken from the parameter supplied by the external functions
def outer_func(msg):
def inner_func():
print(msg)
return inner_func()
hi_func = outer_func('Hi')
hello_func = outer_func('Hello')
Showing the outer function taking an argument. Again the inner function is looking to the outer function for an argument and retrieves the argument received by the outer function. This allows the closure to be reusable. Assigning custom function labels to the outer function allows for different parameters to be passed into the function. Giving different answers.
# Closure 3
# A lot more going on here to show the benefit of the closure
import logging
#This is to capture information of the function and arguments
logging.basicConfig(filename='test.log', level=logging.INFO)
def logger(func):
# Here is the closure getting used to log rather than
# be the composition function
def log_func(*args):
logging.info(f'Running {func.__name__} with arguments {args}')
print(func(*args))
return log_func
# Functional Parameters being actioned
# Functions to be monitored by logger
def add(x,y):
return x+y
def mul(x,y):
return x*y
# Preparing the parameter function for the logger
add_log = logger(add)
mul_log = logger(mul)
# Function calls with the parameters of the functions
add_log(3,3)
mul_log(4,5)
add_log(12,23)
mul_log(2,100)
The final Closure shows the closure being used for a purpose that is not the computation but for logging information about the computation. Extending the use of the Closure 2 to not only carry out multiple computation but give the ability to log what happened in each on a a log file (test.log)
Comments