snippetpythonTippendingCanonical
Python walrus operator for assignment in expressions
Viewed 0 times
Python 3.8+
walrusassignment-expressioninlinewhilecomprehension
Problem
Need to both compute a value and check a condition, leading to redundant computations or awkward temp variables.
Solution
Use := (walrus operator) for inline assignment:
# Read until empty line:
while (line := input()) != '':
process(line)
# Avoid double computation:
if (n := len(items)) > 10:
print(f'Too many items: {n}')
# In list comprehensions (filter and transform):
results = [
transformed
for item in items
if (transformed := expensive_transform(item)) is not None
]
# Regex matching:
import re
if m := re.match(r'(\d+)-(\d+)', text):
start, end = m.groups()
# While loop with assignment:
while chunk := file.read(8192):
process(chunk)
# In any() / all():
if any((found := item).price > 100 for item in catalog):
print(f'Expensive item: {found.name}')
# Don't overuse! Keep it simple:
# BAD - hard to read:
# if (x := f(a)) and (y := g(x)) and (z := h(y)): ...
# GOOD - just use variables:
# x = f(a); y = g(x); z = h(y); if z: ...
# Read until empty line:
while (line := input()) != '':
process(line)
# Avoid double computation:
if (n := len(items)) > 10:
print(f'Too many items: {n}')
# In list comprehensions (filter and transform):
results = [
transformed
for item in items
if (transformed := expensive_transform(item)) is not None
]
# Regex matching:
import re
if m := re.match(r'(\d+)-(\d+)', text):
start, end = m.groups()
# While loop with assignment:
while chunk := file.read(8192):
process(chunk)
# In any() / all():
if any((found := item).price > 100 for item in catalog):
print(f'Expensive item: {found.name}')
# Don't overuse! Keep it simple:
# BAD - hard to read:
# if (x := f(a)) and (y := g(x)) and (z := h(y)): ...
# GOOD - just use variables:
# x = f(a); y = g(x); z = h(y); if z: ...
Why
The walrus operator eliminates redundant calculations and makes while-loop patterns cleaner. Use sparingly for readability.
Revisions (0)
No revisions yet.