newbie: binding args in callbacks

Edward K. Ream edream at tds.net
Wed Jul 10 11:27:09 EDT 2002


Alex Martelli wrote:

> Sure.  You need to "snapshot" the value of val at the moment you're
> interested in it -- passing it as an argument is one way to do that.
> 
> In the for loop that you show, the use of val in:
>    callback=lambda: self.myCallback(val)
> indicates the variable thus named in outer scope (or global scope),
> and the relevant value is the one that said variable has _when
> the lambda is later called_ -- by what time the loop has proceeded
> to the end and val has stayed bound to the last value.

Thanks very much for this clarification.

> BTW, the for loop using:
> 
>    callback = lambda val=val: self.myCallback(val)
> 
> should work just fine -- now you're "snapshotting" again (passing
> val as an argument, so the value that matters is here the one at
> *function-definition* time, as in the "extra level of indirection"
> case that I suggest, NOT the value at *function-call* time in the
> outer or global scope).

Yes.  This does work.

Edward
--------------------------------------------------------------------
Edward K. Ream   email:  edream at tds.net
Leo: Literate Editor with Outlines
Leo: http://personalpages.tds.net/~edream/front.html
--------------------------------------------------------------------



More information about the Python-list mailing list