Common LISP-style closures with Python
Antti J Ylikoski
antti.ylikoski at tkk.fi
Fri Feb 3 19:27:56 EST 2012
In Python textbooks that I have read, it is usually not mentioned that
we can very easily program Common LISP-style closures with Python. It
is done as follows:
-------------------------------------
# Make a Common LISP-like closure with Python.
#
# Antti J Ylikoski 02-03-2012.
def f1():
n = 0
def f2():
nonlocal n
n += 1
return n
return f2
-------------------------------------
and now we can do:
-------------------------------------
>>>
>>> a=f1()
>>> b=f1()
>>> a()
1
>>> a()
2
>>> a()
3
>>> a()
4
>>> b()
1
>>> b()
2
>>> a()
5
>>> b()
3
>>> b()
4
>>>
-------------------------------------
i. e. we can have several functions with private local states which
are kept between function calls, in other words we can have Common
LISP-like closures.
yours, Antti J Ylikoski
Helsinki, Finland, the EU
More information about the Python-list
mailing list