43

Try out walrus operator in Python 3.8

 5 years ago
source link: https://www.tuicool.com/articles/hit/Iz67n26
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

The first alpha of Python 3.8 was just released at February 3, 2019. With that comes a mayor 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 .

jeYRvuE.jpg!web

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 .

FNNne2j.png!webnmuMRrZ.png!web
aAbUz2e.jpg!web
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.

aAbUz2e.jpg!web

Luckily for us this is quite easy to fix.

aAbUz2e.jpg!web
Fix the zlib related problems like this

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

veuEFrE.png!web3ayQRfm.png!web
Install the alpha with pyenv install 3.8-dev
aqUZjqu.png!webR3Qv2iq.png!web
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.

qiAJzeZ.jpg!web

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.

aAbUz2e.jpg!web

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK