Lambda returning tuple question, multi-expression

Thomas Passin list1 at tompassin.net
Thu Mar 9 15:25:08 EST 2023


On 3/9/2023 3:29 AM, aapost wrote:
> The 'what I am trying to do' is ask a question regarding opinions and 
> practices on issuing a sequence of actions within a lambda via a tuple 
> (since the common practice approaches against it - mainly with tkinter - 
> feel more convoluted), and in doing so leaving it open ended to get a 
> feel on what opinions are, and to see if any opinions influence mine.

I finally realized why I am uncomfortable with doing this kind of thing. 
  It's because, IMHO, lambda expressions should not have side effects 
and should not require much mental effort to grasp what they do.  Yes, 
you can do so.  You can even print from a lambda (and it might be useful 
for debugging):

lambda x: print(f'The lambda received {x}') or x*x

The Python Reference on readthedocs.io also has a tk example that 
specifically wants the side effect (see 
https://python-reference.readthedocs.io/en/latest/docs/operators/lambda.html):

 >>> # this is a code snippet from a Tkinter gui app
 >>> # in this case lambda is quite convenient
 >>> self.btn_cancel = Button(self.progress_container, text='Cancel',
 >>>     command=lambda: subprocess.call('taskkill /f /im uberzip.exe',
 >>>     shell=True))

Maybe so, but I think it's better not to have side effects hidden away 
in expressions that are hard to read and understand.  And being 
anonymous, there is no function name to remind you what the action is 
suppose to do. Much better (still IMHO, of course):

def kill_uberzip():
     """Kill an external running program named uberzip.exe."""
     subprocess.call('taskkill /f /im uberzip.exe', shell=True))

self.btn_cancel = Button(self.progress_container, text='Cancel',
      command = kill_uberzip())

This way, it's easy to understand what btn_cancel() will do each time 
you scan that line of code.  Using the lambda makes you reparse the line 
and spend mental effort each time you scan it.  And this way, you know 
directly that the button is going to cause a side effect outside your 
program, which you have to infer (an indirect mental operation) when you 
scan the lambda.

For this particular example, it might turn out that there could be more 
than one instance of uberzip.exe running at the same time.  Which one 
should be killed, and how do you kill the right one?  With the function, 
you can get those details under control, but I hate to think what might 
happen to the lambda expression.

Yes, of course, there can be times when the lambda expression is 
somewhat easy to understand and the side effects are harmless.  In that 
case, it may be easy enough to grasp quickly that the anonymous function 
would not benefit from having a name.  So OK, it's not a hard-and-fast 
rule.


More information about the Python-list mailing list