The order of execution #16292
-
I sometimes have a guess at the sequence in which upython does things and come up wrong. In the examples below boot_modem & _attached() are functions that return 'OK' or None. If I run
all is good. But my original idea
crashes saying integers aren't iterable, which means the walrus hasn't run before the 'OK' in r check & r must still be zero. I don't understand why that is? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
The ›new‹ r hasn't been defined at this point, the ›old‹ r is still an integer 0. if (r := (boot_modem() and attached())) and 'OK' in r: and all is well. |
Beta Was this translation helpful? Give feedback.
-
Yes. It's usually wise to put assignment expressions in parens. The following works as expected: >>> r = 0
>>> if (r:= 1) and r==1: print(f"r = {r}")
...
r = 1 But this does not: >>> r = 0
>>> if r:= 1 and r==1: print(f"r = {r}")
...
>>> r
False
>>> because the latter is effectively doing if r:= (1 and r==1): print(f"r = {r} which sets r |
Beta Was this translation helpful? Give feedback.
Yes. It's usually wise to put assignment expressions in parens. The following works as expected:
But this does not:
because the latter is effectively doing
which sets r
False
(because the comparison returnsFalse
).