Python walrus operator
I recently discovered the assignment expression, also known as the walrus operator, which was introduced in Python 3.8
Here is how it works in several examples:
Let’s consider the following data structure:
fresh_vegetables = {
‘tomatoes’: 10,
‘cucumbers’: 8,
‘onions’: 5
}
Lets make a salad out of these vegetables:
if (count := fresh_vegetables('tomatoes', 0)) >= 2:
pieces = slice_tomatoes(count)
else:
pieces = 0
try:
salads = make_salad(pieces)
except OutOfTomatoes:
out_of_stock()
This is much more readable than the example without the walrus operator:
def make_salad(count):
....
pieces = 0
count = fresh_vegetables('tomatoes', 0)
if count >= 2:
pieces = slice_tomatoes(count)
.....
Using the walrus operator gives us better readability of our code and less code lines to write and maintain.
It works too with a do/while loop construct.
Instead of
def pick_vegetables():
....
while fresh_vegetables:
for vegetable, count in fresh_vegetables.items():
batch = make_salad(vegetable, count)
fresh_vegetables = pick_vegetables()
We do the following with the walrus operator:
while fresh_vegetables := pick_vegetables():
for vegetable, count in fresh_vegetables.items():
batch = make_salad(vegetable, count)