scoping weirdness
Alex Martelli
aleax at aleax.it
Mon Aug 27 06:06:21 EDT 2001
"Tim Peters" <tim.one at home.com> wrote in message
news:mailman.998804559.5680.python-list at python.org...
...
> > def press_button (text):
> > print 'you pressed %s' % text
> >
> > def create_button (label):
> > func = lambda: press_button (label)
> > Button(root,text=label,command=func).pack()
> > # if I put more stuff here and set label to something new,
> > # the button doesn't do what I expected.
...
> Pick one:
[snipped 5 ways to curry without calling it currying:-)]
Or pick another (explicit currying), e.g. with
"from __future__ import nested_scope" if need be:
def curry_to_argumentlessness(*args, **kwds):
def totally_curried_function():
return args[0](*args[1:],**kwds)
return totally_curried_function
then use it at will, e.g.:
def create_two_buttons(label):
Button(root, text=label, command=
curry_to_argumentlessness(press_button, label)
).pack()
label = label.upper()
Button(root, text=label, command=
curry_to_argumentlessness(press_button, label)
).pack()
Currying-to-argumentlessness is a frequent enough need
(since Tk &c all want lots of argumentless callables)
that one may want to rename 'curry_to_argumentlessness'
to something more concise and put it in sitecustomize
or thereabouts. Hmmm, there's lot of good currying stuff
already on the Cookbook, but presented in a much more
general way - I'm wondering if this extremely frequent
special case warrants its own recipe...
Alex
More information about the Python-list
mailing list