Understanding the walrus operator := in python 3.8
For years, programmers have used = as a way of expressing assignment. Some may argue that it’s one of the worst language decisions as = describes equality and <- is shows assignment. Either way, we as humans have learned and continued to create more and more complex code using = because we’ve kept consistency. In python 3.8, this consistency was changed. Was it for the better? Well, we’ll have to find out!
What does the := do?
At a very high level, the walrus operator allows you to do variable assignment and then return the value that is being assigned to the variable all by choosing := (our friend walrus) over =. What’s even more exciting is that the value assigned can be any valid expression other than an unparenthesized tuple!
(var := expr)
In the example below, you can see that we want to print the value of y after assigning the result of f() to it. As we can see, by using the new walrus operator, we can complete this task in one line of code. Very pythonic.
print((y := f())) # instead of writing y = f() print(y)
Although a trivial example, this will become more clear why this new operator can be very useful for expensive tasks like database calls, file I/O, and just general cleaner code.
Real-world use cases
The previous example did throw my mind a curveball (reading the walrus operator just hasn’t naturally clicked yet). Although, I find it to be very interesting for practical applications.
Some of the big issues that the walrus operator tackles are extra lines of code to perform the same task and only calling expensive tasks (File I/O, DB, server requests, etc) once and in the time that you need them. For instance, you might find for a while loop, you prime a variable before checking the condition or have a while 1 (if you’re a classic C programmer I’m sure you’ve done this) to keep a loop going until some condition eventually breaks us out of the loop. Now, with the walrus operator, we can get rid of previous cases of priming variables for while loops and calling expensive expressions multiple times. Let’s look at some more practical examples and see how this new operator would be used!
Reading bytes from a file
When reading from a file in a way that you want more control by reading bytes, you might find that the walrus operator will make your life a lot less cluttered. Before we had the walrus operator, we had to prime data, run the conditional check of the while loop in a separate line, process it, and then prime it again! That’s 4 lines of code. With the walrus operator, it’s only 2. Honestly, I think it’s easier to understand as well.
# now while data := file.read(256): process(data) # prev data = file.read(256) while data: process(data) data = file.read(256)
List comprehensions are another feature of python that you could argue is confusing if you’ve never seen them, but gives you the power to make your life easier if you choose to utilize its powers. This next example is going to show you a way to use the walrus operator in a list comprehension where you previously had to call the expression twice. Having to evaluate an expression twice could be very costly depending on the computation of the expression.
# now data_points = [(x, y) for x in x_coordinates if (y := f(x)) < threshold] # prev data_points = [(x, f(x)) for x in x_coordinates if f(x) < threshold]
Even though these are the same number of lines of code, the computation used in the first example has the potential to be much less than the computation in the second example. This is because we were able to evaluate and expression and store the result for use later, where previously, the expression, f(x), would be evaluated twice.
Other use cases
To find other use cases for the walrus operator, I would look for code that assigns an expression to a variable and then checks conditions with that variable. By using the walrus operator here, you will be able to shave off some lines which may or may not make your code more readable for future developers.
Another use case would be any form of python comprehension (dictionary, list, etc) and taking away the double expression evaluation by using the walrus operator. By using the walrus operator here, you will be able to remove excess computation performed by your program which could be HUGE if it’s very computationally expensive.
If you find other use cases, let me know!
I’m not entirely sold on the walrus operator. I think that it a long way to go with adoption from the python community. Although I can see practical use cases, it just hasn’t sat right with me yet. My big issue with the walrus (no offense to the actual animals, I love them) is that it’s easy to misuse. For instance, I could see a novice programmer writing statements like this in their code because they don’t know the difference yet between the assignment and walrus.
(name := "brady") (greeting := "hello") print(greeting) print(name)
Is it their fault that we made python more complex? Absolutely not! But if this is a design decision that we’re going to make as a community, there needs to be a bigger push to get the knowledge out for up and coming developers to understand how this operator is used and when they should use it. Especially considering a foundational pillar of python is that there is only one clear and natural way to do something.
Does adding the walrus still maintain that pillar? I would have to say yes*. Where the asterisk states the risk of being confused between assignment and walrus if you’re a new programmer. Either way, that’s why I make these articles in my free time. I want to spread this knowledge so more developers can be aware of these changes and be better at what they do!
Today we talked about the new walrus operator that has been released with Python 3.8. Link to the release docs here. We learned how the walrus operator differs from the assignment operator as well as understanding when to use the walrus operator.
What do you think of the walrus operator? Do you think it will be easily adopted by the community, or do you think it will have some ways to go with the refinement of use case understanding?
If you like today’s post, make sure to sign up for my email list so you stay up to date with all of the new content coming out on unwrapped bytes!