Tk Dynamic Menus problem

Fredrik Lundh fredrik at pythonware.com
Wed Jul 24 21:00:26 EDT 2002


Jeremy Bowers wrote:

> > I'm not exactly sure why it's printing '3', but you do have a scoping
> > problem there.
> > Replace 'lambda: printFunc(i)' with 'lambda i=i: printFunc(i)'. Supplying i
> > as a keyword arg for the lambda brings i into the labmda's scope.
>
> Thanks, that did it.
>
> I would be interested in a bit more explanation though. In the "real"
> application, "i" were instances, not numbers (if that matters). Why would
> the 'i' in the previously created lambda commands "shift" to follow the
> outside value of i?

in your original code, your lambda contained a reference
to the name "i" in an outer scope.

when the lambda was called, it would fetch the *current*
value of "i" from that scope (that is, the last value that the
variable had before you returned from the function).

in contrast, the "i=i" pydiom binds the *value* of the outer
"i" to a local lambda variable with the same name.  if you re-
bind the outer "i", the local variable still points to the same
value.

</F>





More information about the Python-list mailing list