scoping weirdness

Carel Fellinger cfelling at iae.nl
Sat Aug 25 18:36:52 EDT 2001


Paul Rubin <phr-n2001 at nightsong.com> wrote:
...really helpful answer that was wiped out prematurely snipped
> Yes, let me go up a level and ask if there's a better way to do this.
> It's for Tkinter--say I want several buttons that all call the same
> function, giving the button text as an argument.  My code looks
> something like:

>     from __future__ import nested_scopes

Ah, your were relying on nested scopes. They were ment to save us from 
users wondering why their vars weren't visible inside their lambda's,
but now we get "help my lambda keeps seing the var in the enclosing block"

Thank god the old way of dealing with this still works: curry.
Either with a class or by feding arguments to the lambda at definition time.

>     def create_button (label):
>       func = lambda: press_button (label)

replace the above with:

   func = lambda label=label: press_button (label)

or use a class based cury (better classes to be found in the cookbook
and the c.l.py archives):

   class Cury:
       def __init__(self, fun, *args, **kws):
          self.fun, self.args, self.kws = fun, args, kws

       def __call__(self, *event):
          # let's put an event arg here so this same code can be used
          # for Tk callbacks that pass an event as you will need that too.
          # we arbitrary place it upfront, and we use an arg list
          # as that saves us from having to choos a default value that
          # would signal not to pass it on.
          return self.fun(*(event+self.args), **self.kws)

   func = Cury(press_button, label)        

-- 
groetjes, carel



More information about the Python-list mailing list