Photo by Jay Ruzesky on Unsplash

Walrus to the Rescue!

Using Python 3.8 Assignment Expressions :=

Miki Tebeka
The Pragmatic Programmers
2 min readNov 23, 2021

--

🎁 Black Friday Sale. Our annual sale is on now through November 29, 2021 — save 40 percent on ebooks on The Pragmatic Bookshelf website using code turkeysale2021. For Turkey Day, we are featuring all Python books, including Miki Tebeka’s Python Brain Teasers.

Let’s say you have a publisher of messages, that sometimes sends an empty message:

You’d like to collect only the non-empty message from a list of publishers, so you try this:

The output is not what you expected:

Looking at the code, the reason becomes obvious: you call p.get() twice. The filter ( if p.get().strip()) is called first, and then the expression one on the left.

Looks like you’ll need to rewrite the code without list comprehension:

This prints out the expected result:

However, instead of a single line, you now have five to create and populate messages. Since there's a positive correlation between the number of lines of code and the number of bugs, less code is better (but not at the expense of readability).

What can you do? The walrus operator to the rescue! Python 3.8 added assignment expressions (known as the walrus operator since := looks a bit like a walrus emoticon), and they are really helpful in list comprehension.

Here’s the new code, which prints out the expected result.

The walrus operator is still fairly new (Python 3.8 came out in 2018) and the community is still figuring out the best ways to use it.

How do you use :=?

--

--