The walrus simultaneously names the value being tested so you can refer to it within the condition; it's sort of the inverse of Perl code using $_. So instead of
if (do_something()) {
act_on($_);
}
you have if placeholder := do_something():
act_on(placeholder)
But when reading aloud, however you'd read the perl will flow as more natural english. "If the string contains z, do something with it".If you really want to read the Python as it's written, it corresponds to the second of these sentences:
- If the substring from 3 to 5 is "fg", crash.
- If variable_name, the substring from 3 to 5, is "fg", crash.
Once way to test if this works is to take the code, read it aloud, and then use the read-aloud version to rewrite the code. If you don't have a high degree of certainty that you end up with the same code, something has failed along the way.
In this case, if I take "if x:= y()" and read it aloud as "if y", I think the vast majority of people would translate that to code as "if y():", which isn't the same thing.
1. You read more than one line of code.
2. Executing the code in the conditional more than once doesn't matter.
If you meet those two assumptions, then the reading I suggested will transform this
if x := y():
act_on(x)
into this if y():
act_on(y())
which is, in fact, the same thing.For what it's worth, "x = y()" is one of the harder things for new programmers to translate to English in the first place -- it reads most naturally as "x equals y," but leads to better intuitions as "x gets the value of y". I think that's what makes this clunky to verbalize, rather than the "if truthy" bit.
> For what it's worth, "x = y()" is one of the harder things for new programmers to translate to English in the first place
Right... so why have we added more complexity to something known to be very complicated?
No, “if <expression>” expands to “if <expression> has a truthy value”.
“<var> := <expression>” is itself an expression, which can be best (IMO) read in English as “<var> (which is <expression>)”
“... x := foo ...” is read “... x, which is foo, ...”