lambda closure question

jfj jfj at freemail.gr
Sat Feb 19 14:50:45 EST 2005


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!

Nested functions, seem to do two independent things:
   1) reference variables of an outer local scoope
   2) are functions bound dynamically to constants

These two are independent because in:
##############
def foo():
     def nested():
          print x
     f = nested
     x = 'sassad'
     f()
     x = 'aafdss'
     f()
     return f
##################

once foo() returns there is no way to modify 'x'!
It becomes a kind of constant.

So IMVHO, one will never need both features. You either want to
return a function "bound to a local value" *xor* "use a local
function which has access to locals as if they were globals".

Supposing the default behaviour was that python does what Carl
suggests (closures don't keep track of variables), would there
be an elegant pythonic way to implement "nested functions that
reference variables from their outer scope"? (although if find
this little useful and un-pythonic)

Personally, i think that this is a problem with the way lisp
and other languages define the term "closure". But python is
different IMO, and the ability to reference variables is not
useful.


cheers,

jfj
---------------
# the president



More information about the Python-list mailing list