[Tutor] lambda in a loop
Christian Wyglendowski
Christian.Wyglendowski at greenville.edu
Thu Nov 17 15:58:33 CET 2005
Fred said:
> >> Obviously, the lambda is using "value" at the end of the loop (4),
> >>rather than what I want, "value" during the loop (0,1,2,3).
Christian said:
> > Right. I think the issue is that your lambda calls another funtion.
> > However, the function isn't called until the lambda is called later,
> > when value == 4.
Kent said:
> No, the problem is not when the function is called, but when
> value is bound into the closure.
I don't think that the value is being bound into the closure, though.
It is using the global 'value', which is why I said "the function isn't
called until the lambda is called later, when value == 4". I should
have been more clear and said "when global value == 4".
I think this can be demonstrated by adding a "del value" statement after
the loop. Here is the traceback I get after adding that statement:
Traceback (most recent call last):
File
"C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py"
, line 310, in RunScript
exec codeObject in __main__.__dict__
File "C:\Documents and
Settings\cwyglendowski\Desktop\cp_playground\lambdatest.py", line 12, in
?
c()
File "C:\Documents and
Settings\cwyglendowski\Desktop\cp_playground\lambdatest.py", line 7, in
<lambda>
commands.append(lambda:doLambda(value))
NameError: global name 'value' is not defined
Christian said:
> > I'd use a closure rather than a lambda.
Kent said:
> The original solution does use a closure.
Thanks for pointing that out. I don't use lambda often and didn't think
about how you can create closures with lambda statements.
Kent said:
> The problem is that
> variables are not bound into a closure until the scope of the
> variable exits. That is why using a separate factory function
> works - the closure is bound when the factory function exits
> which happens each time through the loop. In the case of
> closures in a loop the closure is not bound until exiting the
> scope containing the loop and all the closures are bound to
> the same value.
I'm not even going to go there ... Danny just wrote an excellent book on
this :-)
Thanks to all for the great discussion.
Christian
More information about the Tutor
mailing list