PEP 572. Love it or hate it (you should love it), it is now merged into python and will be released in python 3.8. I had an initial negative reaction to this PEP, however I’ve come around! When this PEP was proposed, I was not coding in python full time. I was working on pipenv during my spare time and I didn’t see much use for it, hence I found it an unnessasary addition. I now have a job where I code in python full time and I have seen many places in our code base where this can be used!
The aim of this post is to show how it can be very useful, and that change, while scary, can be a good thing! Any time I find a use for it in any code base I work on, I’ll make an entry to this post! Let’s get started!
What is it?
PEP 572, entitled assignment expressions, adds a way to assign variables within an expression. The operator to do this is
:=, or as some people have been calling it, the walrus operator. Let’s look at a simple example.
# without assignment operator import re match = re.search('^FOO','FOOBAR') if match: print(match.group(0))
# with the assignment operator import re if match := re.search('^FOO','FOOBAR'): print(match.group(0))
This is a very simple example, saving one line of code, although it’s a pattern I use often at work. Let’s break it down…
In the first code snippet, we are doing pretty standard stuff. We set
match equal to the result of
re.search(). Next if
match is not a
NoneType print out the first group. Let’s save a line of code by introducing the assingment operator. Instead of assigning
match first, we assign it in a conditional expresion. It basically reads match becomes the retured value of
re.search() and then the contional is evalluated against the value of
match which also becomes a valriable in the current scope. Again this is an extremely trivial example. I could write some made up super complicated ways to use the assignment operator, however that’s not real life, that’s not how I’m going to use the assingment operator, at least not at this time. I would reccomend reading the importance of real code from the PEP 572 proposal. That is one of the reasons I wanted to make this blog post. I want to post actual examples from code bases I work on, where it just makes sense to use the assignment operator.
with open('source.txt', 'r') as src, open('dest.txt', 'w') as dest: while True: chunk = src.read(1024) if not chunk: break dest.write(chunk)
with open('source.txt', 'r') as src, open('dest.txt', 'w') as dest: while chunk := src.read(1024): dest.write(chunk)
More to come as I work through more of my code bases!
This PR has a lot of examples of places in the standard library where the assignment operator is being used with while statements in python 3.8. Similiarly this PR contains places in the standard library where the assignment operator is being used for match/group capture along with this PR that contains examples of using the assignment operator in a list comprehension.