O'Reilly logo

Python Unlocked by Arun Tigeraniya

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required