Try out walrus operator in Python 3.8

Get started with Python 3.8 alpha 1

The first alpha of Python 3.8 was just released at February 3, 2019. With that comes a major new feature in the form of PEP 572, Assignment Expressions, implemented by the amazing Emily Morehouse, Python Core Developer and Founder, Director of Engineering at Cuttlesoft.

What’s a walrus operator?

Walrus-operator is another name for assignment expressions. I think the official PEP does an excellent job of explaining the semantics.

Syntax and semantics

In most contexts where arbitrary Python expressions can be used, a named expression can appear. This is of the form NAME := expr where expr is any valid Python expression other than an unparenthesized tuple, and NAME is an identifier. The value of such a named expression is the same as the incorporated expression, with the additional side-effect that the target is assigned that value:

This new operator has gotten sparked some lively opinions and debates, this article will not focus on that part. As many other I’m excited to try this out and see how it could be used in my own code, and that is the focus of this piece.

To get started we need to install Python 3.8, to ease switching between version I use a tool called pyenv. Details on how to install pyenv can be found here.

Short version for macOS users

At this point run pyenv init and follow the instructions.

Now lets install the development-version of python 3.8 using pyenv and set our shell to use this version, pipenv is also an alternative which wraps pyenv. But first we need to install and link zlib, otherwise you’ll run into the following error.

Luckily for us this is quite easy to fix.

Fix the zlib related problems like this

At this point you can simply install python 3.8 using pyenv.

Install the alpha with pyenv install 3.8-dev

Voila we can now use Python 3.8 by running pyenv shell 3.8-dev

Victor Stinner, Python Core Developer wrote a pull-request back in July showcasing how the walrus-operator could be used in the python standard library, it’s a great way to see how this new syntax can be used.

Let’s try to use it ourselves! I’m going to write a piece of code using pre-3.8 syntax and then the same code with walrus operators. I created some dummy data based on jsonplaceholder where I want to check if a property exists and then print it.

There you have it, Python 3.8 alpha up and running with a working copy of the walrus operator. Now it’s time to experiment more with this and put it to good use! Check out the official PEP for more detailed examples and the release notes for details on what more new things you can find in the 3.8a1 release.