lambda closure question
Carl Banks
invalidemail at aerojockey.com
Sat Feb 19 05:21:42 EST 2005
jfj wrote:
> Carl Banks wrote:
> > Ted Lilley wrote:
> >
> >
> >>Unfortunately, it doesn't work. It seems the closure keeps track
of
> >>the variable fed to it dynamically - if the variable changes after
> > [...]
> >>
> >>At least, that's the explanation I'm deducing from this behavior.
> >
> >
> > And that's the correct explanation, chief.
>
> >
> > It is intended that way. As an example of why that is: consider a
> > nested function called "printvars()" that you could insert in
various
> > places within a function to print out the value of some local
variable.
> > If you did that, you wouldn't want printvars to print the values
at
> > the time it was bound, would you?
>
> Allow me to disagree (and start a new "confused with closures"
thread:)
>
> We know that python does not have references to variables. To some
> newcomers this may seem annoying but eventually they understand the
> pythonic way and they do without them. But in the case of closures
> python supports references!
That's right. It's called Practicality beats purity.
The question is what's more important: to be able to use a nested
function to reference the outer scope, or to be able to use a nested
function as a closure inside the function it was defined in? (Both
approaches effectively allow using a nested function as a closure if
it's used after the function returns.)
The Gods decided, for practical reasons, the former was more important.
My experience bears this out: I find that about half the nested
functions I use are to reference an outer scope, half I return as a
closure. Only once or twice did I try to use a nested function inside
the defining function. I would guess this is more or less typical of
how nested functions are used. If so, it was the right decision.
--
CARL BANKS
More information about the Python-list
mailing list