Returning values from a lambda

William Tanksley wtanksle at
Fri Nov 16 18:45:18 CET 2001

On Fri, 16 Nov 2001 12:07:05 +1000, 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,
>> Wait a second.  You don't want to return values; you want to modify
>> variables.  There's a HUGE difference; lambdas can do the first, but they
>> don't support any of the syntax to do the second.

>> 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.

You can wrap a lambda around the function, if you'd like; or you can
access the variables directly in the function itself (it helps to be using
the new scoping code, but that's not essential).

>>>def operations(a,b):
>>> return a+b, a*b

>> def operations(a,b):
>>    x = a+b
>>    y = a*b

>Indeed I could do it like that, but I would need to define globals for x 
>and y.  Can this be done without using globals ?

Your original example used x and y.  My reply, therefore, used them as
well.  What do you want me to use?

The best way is to communicate through an object.  Try something like this:

class something:
 def myfunc():
  r = MyButtonResponse()
  b = Button(..., lambda r=r: setButtonClicked(r)

'r' is the response object, contains the needed returns, and can be
examined at your convenience.  You could also have it be a member
variable, of course.

-William "Billy" Tanksley

More information about the Python-list mailing list