[Tutor] Multiple buttons, One callback (fwd)

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sun Sep 18 03:09:05 CEST 2005

> So, just to see if I understand you, I can create a function that
> creates the thunk callback and returns it.  This returned thunk callback
> (is that a technical term or one of your own, by the way?) can then be
> bound as the button's call back and will be able to remember the
> parameters passed to the thunker -- the function creating the thunk
> callbacks.

Hi Dash,

Like most technical words, "thunk" is overloaded, and it has several
meanings, depending on who you're talking to.

I'm using the definition from the Lisp tradition: in the Lisp programming
language, a "thunk" is a function that doesn't take arguments.


(Confessional aside: I've been learning how to programming in the PLT
Scheme language recently, and I'm starting to absorb more and more of the
terminology into myself.  In the PLT documentation, they use the word
"thunk" all the time.  I apologize if this is making things confusing, but
I really have no control over this.  *grin*)

But anyway, going back to that example code,

>>> def make_msg_thunk(msg):
...     def thunk():
...         print msg
...     return thunk
>>> msg_callbacks = [make_msg_thunk(m)
...                  for m in ('hello', 'happy', 'world')]
>>> msg_callbacks
[<function thunk at 0x403a610c>, <function thunk at 0x403a6bc4>, <function
thunk at 0x403a6bfc>]
>>> msg_callbacks[0]()
>>> msg_callbacks[1]()
>>> msg_callbacks[2]()

We're taking advantage of a feature called "lexical scope": the thunk
function is physically nested and defined where it can see 'msg'.  By
taking advantage of this lexical scoping feature, we have a very
lightweight way of building custom callback functions.

Hope this helps!

More information about the Tutor mailing list