DEV Community

Cover image for Python 3.8's Walrus Operator is (almost) perfect for Jupyter Notebooks
Toshi Kurauchi
Toshi Kurauchi

Posted on

Python 3.8's Walrus Operator is (almost) perfect for Jupyter Notebooks

Assignment expressions, AKA the walrus operator, is (arguably) one of the coolest new features of Python 3.8. Admittedly, I first loved it simply because its name shows that goofiness remains strong in the dev community.

Then I started thinking about possible use cases for it. I read some articles, reflected a little more, and ended up with the impression that it wasn't a bad feature, but wasn't really that useful.

Fast forward to this week. I was teaching a class about basic Jupyter Notebook usage when it struck me that the walrus operator is great for notebooks!

How often do we encounter cells such as these:

Jupyter notebook cell with a line of Python code: variable = do_something() followed by another line of Python code: variable, followed by a DataFrame showing the result.

Essentially, what we want is to assign a value to a variable and then return it to be displayed as the result of the cell. Well, it turns out that that's exactly what the walrus operator is for: assign and return. So now we can have a more concise cell with:

Jupyter notebook cell with Python code: (variable := do_something()) followed by a DataFrame showing the result.

And you can probably see why the title says almost perfect. It would be nice if this simpler version worked:

Jupyter notebook cell with Python code: variable := do_something() followed by a SyntaxError.

However it doesn't, and such is life. Apparently there has been some discussion over this and it will not be supported. So we will have to live with those parentheses for now.

It may still not be that exciting, but I'm happier with the walrus operator after finding this use case, so I decided to share it. Also, before writing this post I did some research and found messages from Vedran Čačić and Carol Willing discussing this use case, so I thought it would be nice to acknowledge them for bringing this up.

Top comments (0)