In Python 3.8 a new assignment expression hit allowing for easier access of variables that are used when being assigned. Here are some tips on how this can be used in your everyday coding.
Wait, what’s an assignment expression?
You may have heard of the term assignment operator and seen its use in the wild when doing things like incrementing a variable by 1 in Python. This is where an operator, like
- is combined with the assignment key
=. For example,
x += 1 which means I’m adding the value of 1 to the variable
So an assignment operator performs an operation and assigns the change to the variable used. Therefore, an assignment expression is where a variable is assigned the result of something, maybe the result from a function.
But how is that different to a normal assignment?
The difference with the new walrus operator is that this assignment can occur where would otherwise be an expression. For example, in an
if statement we have an expression where a comparison is performed. What if in the expression there was an assignment to a variable such that the variable can be used elsewhere in the code?
Take this simple example which I frequently use when scraping websites using Beautiful Soup library and checking if an element exists on the page:
has_elems = soup.find_all("div", class_="find-class") if has_elems: ... do stuff on the has_elems list ...
Throughout this website you’ve seen copious examples in the Python REPL where to evaluate an expression I have used the following type of structure (for example when teaching on how to print a list):
>>> my_dict = ['a', 'b', 'c'] >>> print(my_dict) ['a', 'b', 'c'] >>> my_dict ['a', 'b', 'c']
Notice how in the two outputs of the array above I needed to prompt the REPL to output the result on its own line. For example, the command
print(my_list) prompted to print the result of the variable labelled
my_list to the console window. So too did the line where the variable was the only element on the line.
So what does this new funny looking and named operator actually do?
Instead of using these types of prompts (i.e.
>>> (my_dict := ['a', 'b', 'c']) ['a', 'b', 'c']
Notice that a couple of changes are needed to the code to output the result to the console. Firstly the entire assignment needs to be wrapped in parentheses, otherwise a
SyntaxError results, as shown here:
>>> my_list := ['a', 'b', 'c'] File "<input>", line 1 my_list := ['a', 'b', 'c'] ^ SyntaxError: invalid syntax
Secondly, the assignment equal sign needs to be prefixed with a colon.
So can see you see why they call it the walrus operator?
How Can This Be Useful?
Besides needing fewer lines and code to output a result to the REPL console it could also be very helpful when needing to operate on a result from a function, especially if the result from the function is to be used in the immediate context.
Recently I found myself using the walrus operator when reading data from a file into a list. My process before using the walrus operator was to capture each line, perform an operation on the line being read, and then either print the line or do something with it like inserting the line into a list.
Here is a portion of my original code where I was seeing if a line from a file contained any numerical digits and if it did to print the result:
import re with open('sample.txt') as f: for line in file: digits = re.findall(r'\d+', line) if digits: print(digits)
Using the walrus operator on this simple code reduces it to the following:
import re with open('sample.txt') as f: for line in file: if digits := re.findall(r'\d+', line): print(digits)
As you can see by comparing the above code with the previous code the two lines where the variable
digits captured the result from
re.findall() and is checked against the
if statement both of those lines are compressed into one.
This enables leaner code and is relatively easy for the user to understand what is happening.
The walrus operator is a new assignment operator introduced in Python 3.8 that can enable leaner code by assigning the value of a variable that can be used elsewhere in your code. This can save having to declare the result of the assignment elsewhere in your code as demonstrated above with the regular expression code.