Lambda returning tuple question, multi-expression

Thomas Passin list1 at tompassin.net
Fri Mar 10 23:10:47 EST 2023


On 3/10/2023 10:37 PM, 2QdxY4RzWzUUiLuE at potatochowder.com wrote:
> On 2023-03-10 at 22:16:05 -0500,
> Thomas Passin <list1 at tompassin.net> wrote:
> 
>> I'd make the pattern in this example even more understandable and less
>> error-prone:
>>
>> def update_pids(target):
>>      cmd = ["tail", "-n", "1", "-f", f"/var/log/{target}"]
>>      pids.update({target: subprocess.Popen(cmd)}) if not \
>>          pids[target] else None
> 
> I might be missing something, but how is that more understandable and
> less error prone than any of the following:

The main point is that there can be an easy-to-read and 
easy-to-understand expression to use in the lambda.  I don't care about 
the exact details here.  The command wasn't even mine.  But you only 
have to scan it and grasp it once, in the def:, and then only until you 
get it working.  In the lambda, my suggestions makes it much easier to 
understand what the lambda is expected to do - and it will still be 
clear in three months when the code gets revisited.


>      if not pids[target]:
>          cmd = ["tail", "-n", "1", "-f", f"/var/log/{target}"]
>          pids.update({target: subprocess.Popen(cmd)})
> 
> or:
> 
>      cmd = ["tail", "-n", "1", "-f", f"/var/log/{target}"]
>      pids[target] or pids.update({target: subprocess.Popen(cmd)})
> 
> or:
> 
>      if pids[target]:
>          pass
>      else:
>          cmd = ["tail", "-n", "1", "-f", f"/var/log/{target}"]
>          pids.update({target: subprocess.Popen(cmd)})
> 
> Picking a nit, that's not a good place to continue that line with the
> backslash, either.  
I only continued the line for the purposes of the post because it would 
have gotten line wrapped otherwise. If it were my code in a real module 
I would probably have treated it differently.

 > IMO, "not pids[target]" should be atomic.

Again, it wasn't my code.  I don't even know if the code fragments would 
actually work - they were presented as illustrative examples by the OP. 
And anyway, these nits obscure the point of my post. In a nutshell, it 
is to use good naming and encapsulation to make your code as close to 
self-documenting and as error-free as is reasonably possible, whenever 
you can. Good function names are only one step towards this goal.

Lambdas often work against this goal, so it's worthwhile spending some 
effort to see how to counteract this tendency.

And it's a goal.  You can never meet it 100%.  That's OK.  There will 
always be a matter of taste involved.  That's OK too.  It's still a 
worthwhile goal.



More information about the Python-list mailing list