Try out walrus operator in Python 3.8
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 .
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 .
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.
At this point you can simply install python 3.8 using pyenv.
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.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK