On 3/10/2023 11:15 PM, aapost wrote:
On 3/10/23 22:16, Thomas Passin wrote:
[...]
The additional note in the above is, when taking the def route above, the thing you would have to consider is what scope is the dictionary pids?

Do you need to submit it to the lambda and subsequently the function such as
lambda pids=pids: (
     update_pids("messages", pids),
     update_pids("syslog", pids),

So that update_pids can access it? Or in your design do you have a separate management of it that def update_pids already has access to? (either is valid depending on design intent).

It's easy enough to try out. I'm not going to simulate the dictionary, because it's basically just another argument, and I assume that your example code uses it because it needs to be in that form. For the scope question, see below after the basic example.

>>> def printme(x): print(x)  # Let's not quibble about inline defs!

>>> printme('xxx')
xxx
>>> cmd = lambda x: (
...     printme('this'),
...     printme('is'),
...     printme('a test')
...     )

(Yes, I know it's not recommended to assign a lambda to a variable name, but I'm doing it here just to demonstrate that the lambda works as desired).

>>> cmd(2)
this
is
a test
(None, None, None)

So it executes the intended steps and returns a tuple of three None values, as expected. When used as the target of the "command" arg in the Tk control constructor, I presume the tuple would be ignored just as a return of None would be. But that would need to be tested.

If returning a tuple instead of None were to cause a problem, you could do this:

cmd = lambda x: (
    printme('this'),
    printme('is'),
    printme('a test')
   ) and None

>>> cmd(2)
this
is
a test

But now you are introducing a construct whose purpose is not totally obvious, does not cause any intended effect, and in fact is only required by the nature of the code receiving the callback, which you cannot know by reading this code. So if this construct turns out to be needed, we're forced to take a step away from having the code be as direct and understandable as possible. It's still better in that way than the earlier illustrations (which BTW would also have required the "and None" construct).

To test out the scope question:

>>> def printme(x): print(y)  # Print some other variable, not "x"
>>> y = 'I am y'  # Will "y" get passed through into the lambda?

>>> cmd = lambda x: (
...    printme('this'),
...    printme('is'),
...    printme('a test')
... ) and None

>>> cmd(2)
I am y
I am y
I am y

But maybe the original value of "y" gets baked in at compile time. Let's see:

>>> y = 'I am a post-compile assignment'
>>> cmd(2)
I am a post-compile assignment
I am a post-compile assignment
I am a post-compile assignment

Good, the current value of "y" gets used.

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to