loading...
Cover image for Python SnakeBytes: The Walrus Operator

Python SnakeBytes: The Walrus Operator

codemouse92 profile image Jason C. McDonald ・1 min read

The assignment expression, also known as the walrus operator (:=), was introduced in Python 3.8. An assignment expression performs assignment, while also returning the assigned value from the expression. This allows you to store and test a value in the same line.

temps = [56, 72, 65, 77, 73]

if ((average := sum(temps) / len(temps)) > 80):
    print("It sure is warm!")
elif (average < 50):
    print("It's quite cold.")
else:
    print("Nice weather we're having.")
Enter fullscreen mode Exit fullscreen mode

The average variable was defined within the if expression, so it can be reused in the elif.

When used in a comparison, it may be necessary to wrap the assignment expression in parentheses, as seen here. Otherwise, the result of the comparison will be stored.

But always remember: readability matters. Only use the walrus operator if it will actually make the code more readable. My use of the operator in the example would probably only be justifiable if I don't intend to reuse the average variable outside of the conditional.


PEP 572: Assignment Expression

Discussion

pic
Editor guide
Collapse
renegadecoder94 profile image
Jeremy Grifski

I love that you mention the readability comment at the end! I think I'd have a hard time justifying this operator in almost any context. I'd love to see some other examples. For instance, I just dug up this interesting list comprehension example (source):

employees = [result for id in employee_ids if (result := fetch_employee(id))]

Of course, this is sort of an advanced example which includes a lot of special properties of Python. That said, I like how it looks.

Collapse
mburszley profile image
Maximilian Burszley

It is of great convenience taken from the C languages. I sometimes utilize a similar construct in PowerShell:

if ($var = Get-Service) {
    # do a thing with services
}

Not sure I'd call a list comprehension "advanced"

Collapse
renegadecoder94 profile image
Jeremy Grifski

I'm not sure your example really convinces me that this is a good practice (or a good additional feature for that matter). In fact, it's basically the same example given in the article. What's the advantage of placing the assignment in the condition?

To address your snark, there's a mix of features here which is why I called it advanced:

  • List Comprehension
  • Walrus Operator
  • Type Flexibility (result could be some falsey value)

These aren't exactly loops and conditionals we're talking about. The average person isn't going to be able to understand this line just by looking at it.

Thread Thread
codemouse92 profile image
Jason C. McDonald Author

List comprehensions are pretty normal for some pure-functional languages, like Haskell, but they're rare (and thus feel "advanced") for coders more familiar with, say, C++ or Java.

(The snark definitely wasn't called for.)

Thread Thread
renegadecoder94 profile image
Jeremy Grifski

Agreed! But, there's more to my example than just a list comprehension.

Thread Thread
codemouse92 profile image
Jason C. McDonald Author

Oh, definitely. I think that one would actually make a few of my Python colleagues cringe, with the walrus operator being in it like that...but then, the walrus is controversial to begin with!

Thread Thread
renegadecoder94 profile image
Jeremy Grifski

For sure! I was wondering why they would include the feature because I feel like it goes against Python's design a little bit. For one, it's an expression and a statement which makes it a little ambiguous. Of course, I'm glad that they used a different operator for it.

That said, I just found a really nice example (source):

while chunk := file.read(8192):
  process(chunk)

Now, that's clean!