Functions with state – closures
Key 2: Creating cheap state-remembering functions.
A closure is a function that has access to variables in an enclosing scope, which has completed its execution. This means that referenced objects are kept alive until the function is in memory. The main utility of such a setup is to easily retain some state, or to create specialized functions whose functioning depends on the initial setup:
>>> def getformatter(start,end): ... def formatter(istr): ... print("%s%s%s"%(start,istr,end)) ... return formatter ... >>> formatter1 = getformatter("<",">") >>> formatter2 = getformatter("[","]") >>> >>> formatter1("hello") <hello> >>> formatter2("hello") [hello] >>> formatter1.__closure__[0].cell_contents '>' >>> formatter1.__closure__[1].cell_contents '<'
We can do...