Naming higher order functions
Alex Martelli
aleax at aleax.it
Thu Jan 31 11:11:46 EST 2002
"Achim Domma" <achim.domma at syynx.de> wrote in message
news:a3bpjt$kle$01$1 at news.t-online.com...
> Hi,
>
> this looks interesting to me, but seems not to work with Python 2.1.
Should
> it ? If yes, could somebody explain to me why it works ? ;-)
It works with 2.1 if you put as the first statement of the module:
from __future__ import nested_scopes
In 2.2, you don't need to import anything from the future, since
"the future has come" (with regard to this specific tidbit, i.e.,
scope nesting).
> > def name_me(n):
> > def g(x):
> > return x[n]
> > return g
To make it almost-work in older Pythons, the old trick was:
def makeGetNth(n):
def g(x, n=n): return x[n]
return g
i.e., explicitly naming what can now be obtained as "free
functions" as "default values" for the nested function's
arguments. The "almost" is because one might then, by
mistake, call the returned g with two arguments, and the
second one would take n's place; you have more control now.
As to "why" any of these closures work, well, explanation
depends on your general Python knowledge. Apart from the
issue of the free-variable n (thus of nested scopes), is
the 'working' clear to you?
Alex
More information about the Python-list
mailing list