lambda closure question

Antoon Pardon apardon at forel.vub.ac.be
Mon Feb 21 07:07:33 EST 2005


Op 2005-02-19, jfj schreef <jfj at freemail.gr>:
> 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.

In this particular case yes. But not in general, what about
this:

>>> def F():
...   l = []
...   def pop():
...     return l.pop()
...   def push(e):
...     l.append(e)
...   return pop, push
... 
>>> pop, push = F()
>>> push(1)
>>> pop()
1
>>> push(2)
>>> push(3)
>>> pop()
3
>>> pop()
2

-- 
Antoon Pardon



More information about the Python-list mailing list