Returning values from a lambda

Jeff Shannon jeff at ccvcorp.com
Fri Nov 16 19:14:44 CET 2001


John McMonagle wrote:

> William Tanksley wrote:
>
> > On Fri, 16 Nov 2001 10:36:06 +1000 (EST), John McMonagle wrote:
> >
> >>I wish to return values from a lambda function which is bound to the
> >>Tkinter button command option.  For example,
> >
> > The solution is to not use a lambda.  Just define a function which
> > modifies the variables you need, and pass that function's name in place of
> > the lambda.
>
> But I need to use a lambda in order to pass arguments to the function.

If you want to get fancy, you can create a callable class instance with your
arguments as member variables.  Something like:

class Operations:
    def __init__(self, a, b):
        self.a = a
        self.b = b
    def __call__(self):
        global x
        global y
        x, y = a + b,  a * b

And then use it like so:

btn = Button(root, text'Press Me', command=Operations(2,5))

If you want to avoid using global variables, then you can pre-create your class
instances, and store the results of the operations as another set of member
variables that can be retrieved elsewhere later.

If this looks useful to you, then you may want to search ActiveState's Python
Cookbook for recipes on currying.  My code here is a very simple example of a
concept that is treated in much more detail there.

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list