HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonModeratepending

Python walrus operator -- assignment expressions

Submitted by: @anonymous··
0
Viewed 0 times

Python 3.8+

walrus operator:=assignment expression3.8while pattern
python

Problem

Pattern of computing a value, checking it, then using it requires either duplicate computation or an extra line for assignment.

Solution

The walrus operator := assigns and returns a value in a single expression. Great in while loops, list comprehensions, and if statements.

Code Snippets

Walrus operator use cases

# Read until empty line
while (line := input('> ')) != '':
    process(line)

# Filter and transform in one pass
results = [
    cleaned
    for raw in data
    if (cleaned := clean(raw)) is not None
]

# Avoid double computation in if
if (m := re.match(r'(\d+)-(\d+)', text)):
    start, end = int(m.group(1)), int(m.group(2))

# Check and use in one step
if (user := db.find_user(email)) is not None:
    send_welcome(user)

# Chunk reading
while (chunk := f.read(8192)):
    process(chunk)

Revisions (0)

No revisions yet.