lexical closures and python

Ignacio Vazquez-Abrams ignacio at openservices.net
Thu Sep 6 08:45:36 CEST 2001

On Wed, 5 Sep 2001, John Beppu wrote:

> Hi,
> My understanding is that Python does not support lexical closures.
> I've also heard that it should not be expected to appear any time
> in the near future.  Can anyone confirm or deny this?

Based on what I understand about lexical closures (which, BTW, to begin to
understand I had to go through LISP 101, Beginning LISP, LISP for Dummies,
LISP for Idiots, and LISP for Complete F*cking Morons... ;) ), no, Python does
not support them directly.

You can use a modified/perverted form of them by exploting the fact that
default values in functions are evaluated once only:

>>> def func2(a={}):
...   print a
...   if a=={}:
...     a['foo']='bar'
...   print a
>>> func2()
{'foo': 'bar'}
>>> func2()
{'foo': 'bar'}
{'foo': 'bar'}

but I don't think that that's quite the same thing.

Other than lambdas, you can also mention the map(), reduce(), and filter()
functions, which as I may have heard somewhere do FP-like operations.

Also, I gotta ask: How the hell does JavaScript support them?

Ignacio Vazquez-Abrams  <ignacio at openservices.net>

More information about the Python-list mailing list