Date: February 11th 2016
Last updated: February 7th 2017
Having one function inside another function is called a nested function. Importantly, nested functions can use variables from an enclosing scope (e.g. the inside function can use variables from the outside function, but not the other way around).
After executing a nested function the variables attached to the outer function are remembered and used in subsequent implementation; this is called a closure.
The thing I had trouble with was the fact that the outer function has finished execution after assignment. That is, all subsequent calls are going straight to the inner function and utilising the closure variables. Much like instantiating a class and calling a function.
Create nested function:
def make_multiplier(x): """Generate a multiplier to hold x""" print("multiplier constructed") def multiply(n): """inner function""" print("multiply inside closure") return x*n return multiply
Import closures.py to access functions directly
from closures import * mm = make_multiplier(4) #returns: multiplier constructed # implemment multiply internal method mm(4) #returns: multiply inside closure #returns: 16 mm(1) #returns: multiply inside closure #returns: 4
Use special method to see closure
mm.__closure__ #returns: (<cell at 0x7f6307c87168: int object at 0x9a3440>,) mm.__closure__.cell_contents #returns: 4
Delete the make_multiplier function
del make_multiplier make_multiplier #returns: NameError: name 'make_multiplier' is not defined # note instantiated variable is still in memory mm <function make_multiplier.<locals>.multiply at 0x7f6307c77f28> # evaluate multiplier mm(2) #returns: multiply inside closure #returns: 8