Where Python 3.10’s := Operator Can Be Used
Today I learned how the walrus operator works. I had assumed it could be placed anywhere within an expression; that was incorrect. It can’t be used within an expression. Its proper place is outside and to the left of an expression, but before the if, elif, =, or wherever the expression’s value is going to be used.
As a result, I found myself writing this:
if ua_match := (index < len(robots_lines) and ua_re.match(robotslines[index])):
I needed the if
to fail if index
had reached len(lines)
, but the boolean expression returns its last true value, so the .match() needs to be placed at the end of the expression for the := used before the expression to be able to capture its value. It reads oddly, to be sure.
An intuitive but incorrect approach might be to write:
if ua_match := ua_re.match(lines[index]) and index < len(lines):
but that sets ua_match to True, since the rightmost term of the boolean expression was a comparison. The other intuitive but incorrect approach would be:
if index < len(lines) and ua_match := ua_re.match(lines[index])):
But that doesn’t compile, since placing the := operator inside an expression is a syntax error. It belongs in a new extra layer outside and to the left of the expr but before the leftward if
, elif
, =
or whatever will capture the value of the expression. Here and I thought it could be put anywhere. Its usage is a lot simpler than I took it for.
14 March 2023