How to Use Assignment Expressions in Python

AKA the Walrus Operator
John John (304)
0

Many languages support assignment expressions, and with version 3.8 (PEP 572), Python is joining the party. Assignment expressions allow us to name the result of expressions, which results in cleaner, more concise code.

Previously, this was only possible in statement form, like this:

n = 4
result = n * n  # <= naming the expression result was only possible in statement form
if result > 10:
    print(result)

Assignment expressions, however, allow us to avoid the statement, and assign the value of result right in the conditional expression.

n = 4
if (result := n * n) > 10:
    print(result)

Why is is called the "walrus operator"?

Well, because it looks like a walrus! :=

Now that we've covered the basics, I'll provide some examples where assignment expressions might prove useful.

Posted in these interests:
h/python67 guides
h/code69 guides

When using regular expressions, we often want to test for a match first, then, if they exist, do something with them.

text = 'My zip code is 12345.'

if (matches := re.search(r'(\d{5})', text)):
    print(matches.group(1))

Sometimes when we use while loops we need to compute a value to determine when to terminate the loop. Previously, the assignment would've been a separate statement (actually two, one before the loop and one within). But using the walrus operator we can simplify our code quite a bit.

while rows := result.get_next():
    process(rows)

Another brilliant use case for assignment expressions is within list comprehensions. Sometimes, when we need to compute something inside the filtering condition, we also want to use the computed value in the expression body. This is especially valuable when the computation is expensive.

>>> processed_items = [processed_item for item in items if (processed_item := process(item)]

In the above example, we want to process the item before using it in the conditional. Using an assignment expression allows us to do this, and then use the resulting value in the comprehension body.

Python 3.8 Features
Positional-Only Parameters
Show all in the Python 3.8 Features series
John John (304)
0

If you're familiar with Python's keyword-only arguments, then you've probably wondered why the same constraint doesn't exist for positional arguments. This changes with Python 3.