patternpythonnoneTip
Walrus Operator (:=) for Assignment Expressions
Viewed 0 times
Python 3.8+
walrus operatorassignment expression:=PEP 572while loopcomprehension
Problem
Patterns like compute a value, check it, then use it require either duplicating the computation or introducing an extra variable outside the conditional.
Solution
Use the walrus operator (:=) to assign and test in a single expression.
import re
# Without walrus: separate variable
result = re.search(r'\d+', text)
if result:
print(result.group())
# With walrus: assign and check in one expression
if m := re.search(r'\d+', text):
print(m.group())
# Useful in while loops
while chunk := file.read(8192):
process(chunk)
# Filtering with list comprehension
results = [
clean
for raw in data
if (clean := transform(raw)) is not None
]Why
The walrus operator assigns the result of an expression to a name and evaluates to that value. It reduces redundant computation and makes the compute-check-use pattern concise.
Gotchas
- Walrus operator has lower precedence than most operators — use parentheses when in doubt.
- Variables assigned with := in a comprehension leak into the enclosing scope, unlike regular comprehension variables.
- Overusing walrus in complex expressions reduces readability — prefer explicit variables for non-trivial expressions.
Revisions (0)
No revisions yet.