Walrus operator
The walrus operator := assigns a value to a name and yields that value, so you can bind and test in one expression. It was added in Python 3.8 and is named for the := shape.
Detailed Explanation
Assignment with = is a statement. You cannot write it where Python wants an expression: the condition of an if, a comprehension filter, a while test, a function argument. Before 3.8 you bound a name on one line and tested it on the next. That is still the default style. := is for the case where the extra name exists only to avoid computing something twice.
if (match := pattern.search(text)) is not None: runs the search once, binds match, and tests it. Without the walrus you either call search twice or split the lines. Splitting the lines is clearer when the name lives beyond the test. The walrus is clearer when the name is the test.
Parentheses are often required. := has low precedence, and if match := pattern.search(text) is not None parses as match := (search is not None), which binds a boolean. Put parentheses around the assignment when it sits inside a larger expression.
In a while, while (line := file.readline()) != "": reads and tests in the condition. The older form is for line in file:, which is better for files. The walrus while is useful for sockets, queues, and APIs that return a sentinel.
In a comprehension you can bind an intermediate: [norm for name in names if (norm := name.strip())]. That avoids calling strip in both the filter and the result. Do not use := to sneak statements into a comprehension. If you need two intermediates, use a loop.
The name it binds is in the enclosing scope, not in a new scope. A walrus inside an if leaks the name after the if, like a normal assignment. A walrus inside a comprehension binds in the comprehension's local scope in current Python, which is the opposite of the 3.8 leak that was later treated as a bug and tightened.
:= is not allowed at the top level of an expression statement without parentheses in some versions, and it cannot replace = in an assignment statement. Write count = 0, not count := 0, for ordinary assignment.
Code Examples
import re
text = "order ORD-1044 paid"
if (match := re.search(r"ORD-\d+", text)):
print(match.group()) # ORD-1044
print(match.group()) # still bound after the ifnames = [" ada", "", " linus "]
cleaned = [norm for name in names if (norm := name.strip())]
print(cleaned) # ['ada', 'linus']# Parentheses matter. Without them, `:=` binds the comparison's result.
value = 0
if (n := value) == 0:
print("zero", n) # zero 0Common Gotchas
The name leaks
after `if (user := find()):` you can read `user` below the block, including when the test failed and `user` is `None`.
Do not hide expensive work in a comprehension
one walrus is a readability win. Three is a loop.
Requires Python 3.8+
on older interpreters it is a `SyntaxError`.