I like how := can make a while condition shorter, but it also seems like something a regular assignment can handle. Where is it actually worth using, and is it common in practice?
Do you use Python's walrus operator much?
Answers
It's useful when a condition produces a value you also need in the body. A regex match is a good example: if (match := pattern.match(line)) lets you test the result and then extract its groups without running the match twice.
The same idea works in a comprehension that filters for matches and builds results from them. That can be tidy, though a regular loop is easier to read if the expression gets complicated.
Reply to this answer
Guard clauses are a nice fit too. You can calculate a value in the condition and include that same value in an error message. It avoids either repeating the calculation or giving a one-use variable a separate line.
Watch the parentheses when combining assignment with a comparison. In if (value := calculate()) > limit, value gets the result of calculate(). Without those parentheses, the assignment can capture the comparison result instead.
Reply to this answer
For cache lookups, I like the shape of checking and returning the result in one branch. But if a cached value can be zero, an empty string, or another false value, a truthiness check will treat it as a miss. Compare with None explicitly if that's the miss marker.
Reply to this answer
I mostly prefer a separate assignment. The parentheses rules and the difference between = and := can slow down a reader, especially in a busy condition. Saving one line isn't much of a win if the next person has to stop and parse it.
Reply to this answer
Usage varies. Some people reach for it regularly when it fits, while others rarely use it or avoid it in shared code. The examples here don't tell us how widespread it is across Python projects.
It is syntactic sugar in the sense that you can generally write the logic another way. The payoff is keeping the calculation and the test together when that makes the intent clearer.
Reply to this answer
Add your answer
Answers are reviewed before publication.
c.281~opwicket:
That seems like a good team style question. A short while condition may be clear, while a chain of assignments and comparisons can get ugly fast.