Common LISP-style closures with Python

John O'Hagan research at johnohagan.com
Sat Feb 4 20:31:12 EST 2012


On Sat, 04 Feb 2012 02:27:56 +0200
Antti J Ylikoski <antti.ylikoski at tkk.fi> wrote:

[...]


> 
> # 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
>
 
[...]

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

I'm not sure how naughty this is, but the same thing can be done without using
nonlocal by storing the local state as an attribute of the enclosed function
object:

>>> def f():
...     def g():
...             g.count += 1
...             return g.count
...     g.count = 0
...     return g
... 
>>> h = f()
>>> j = f()
>>> h()
1
>>> h()
2
>>> h()
3
>>> j()
1
>>> j()
2
>>> j()
3

This way, you can also write to the attribute:

>>> j.count = 0
>>> j()
1


John



More information about the Python-list mailing list