Member-only story
Actual, practical uses for the walrus operator in Python (+ examples)
Improving performance or just syntactic sugar?
Quick confession: since its introduction in Python 3.8 I’ve never used the walrus operator that much. When it was first introduced I dismissed it as syntactic sugar and couldn’t really find a reason to use it. In this article we’ll find out whether it just improves our code’s readability or if it’s more that that. We’ll go through some practical use-cases for this obscure operator that’ll make your life easier. At the end of this article you’ll:
- Understand what the walrus operator does
- Know how to use one
- Recognize situations in which to use the walrus operator.
0. What is the walrus operator?
Let’s start at the beginning. The walrus operator looks like this :=
. It allows you to both assign and return a variable in the same expression. Check out the code blocks below
beerPrice = 9.99
print(beerPrice)
On line 1 we assign the value 9.99 to a variable named ‘beerprice’ using the =
operator. Then, on line 2, we print the variable. using the walrus operator we can do both of these operations in one:
print(beerPrice := 9.99)
Now we both print out the beerPrice, that we’ve set to 9.99, in addition we can use the variable for other uses. Easy! Let’s now find out why we would need this functionality and what it means for our code.
1. Use cases for the walrus operator
In this part we’ll apply the operator. I’ll try to illustrate this with a project that resembles a real-life application as much as possible. In my opinion this works a bit better than the “foo” an “bar” examples.
I’ve identified a few situations in which the walrus operator could be practical. First a bit about our project, then we’ll walk through each situation.