| Read it "if y" - that's what's being tested. 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.