Walrus Operator in Python

The Walrus operator := is an assignment operator and is available since Python 3.8.

It is called "walrus operator" due to its resemblance to the eyes and tusks of a walrus.

The walrus operator assigns and returns a value at the same time.

Basic Example

The regular way of asking for a piece of information in a terminal by using the input command is as follows:

>>> age = input('How old are you? ')
How old are you? 30
>>> print(f"You are {age} years old")
You are 30 years old
>>> print(age)
30

Using the walrus operator, you can make this code even shorter:

>>> print(f"You are {(age := input('How old are you? '))} years old")
How old are you? 30
You are 30 years old
>>> print(age)
30

Example with a while loop

Another example using while loops shows how you can simplify the code.

In this snippet, the loop will keep going until the user inputs the number 4.

while True:
    number = int(input("Pick a number: "))
    if number == 4:
        break
    print(f'{number} squared is {number**2}')

To have the same effect with the walrus operator, you do the following.

while (number := int(input("Pick a number: "))) != 4:
    print(f'{number} squared is {number**2}')

A simple test case for the while loop examples above is:

Pick a number: 3
3 squared is 9
Pick a number: 5
5 squared is 25
Pick a number: 4

Example with a Regular Expression

A simple example checking if the letter "Y" exists in "New York".

In the regular way to do it, we first get the result of the search() function, if there is no match, the function returns None which equals to False in the if statement.

If there is a match, the res variable will store a match object and pass the if statement.

import re
text = "New York"
res = re.search("Y", text)
if res:
    print(res.group(0))

To achieve the same result with the walrus operator, we can assign the result of the search() function directly to res in the if statement expression:

import re
text = "New York"
if (res := re.search("Y", text)):
    print(res.group(0))

Example with a List Comprehension

The use of the walrus operator with list comprehensions enables the sharing of a subexpression.

In this case, without the walrus operator, we have to compute the operation n**3 twice because we only want numbers whose cube is greater than 10.

numbers = [1, 2, 3, 4, 5]
new_list = []
new_list = [n**3 for n in numbers if n**3 > 10]
print(new_list)

Using the walrus operator we can save this extra computation and reuse the value of y assigned in the if statement.

numbers = [1, 2, 3, 4, 5]
new_list = []
new_list = [y for n in numbers if (y := n**3) > 10]
print(new_list)

Both will result in the same output, but the walrus operator allows a less expensive computation:

[27, 64, 125]

The code with the walrus operator might seem harder to read for some at first, use it only if it makes sense to you, and if it makes the code better overall.

Controversy

The Walrus Operator was controversial in the community and many people criticized it for some reasons:

  • How will developers even use it?
  • Is this extra complexity needed?
  • This is confusing for new users of the language.

These were the words that Guido van Rossum, the creator of Python, wrote after finishing PEP 572, which gave birth to the so-called Walrus Operator, saying he was resigning from his role.

Now that PEP 572 is done, I don’t ever want to have to fight so hard for a PEP and find that so many people despise my decisions.

I would like to remove myself entirely from the decision process. I’ll still be there for a while as an ordinary core dev, and I’ll still be available to mentor people — possibly more available. But I’m basically giving myself a permanent vacation from being BDFL, and you all will be on your own.

After all that’s eventually going to happen regardless — there’s still that bus lurking around the corner, and I’m not getting younger… (I’ll spare you the list of medical issues.)

I am not going to appoint a successor.

So what are you all going to do? Create a democracy? Anarchy? A
dictatorship? A federation?

I’m not worried about the day to day decisions in the issue tracker or on GitHub. Very rarely I get asked for an opinion, and usually it’s not actually important. So this can just be dealt with as it has always been.

The decisions that most matter are probably

  • How are PEPs decided
  • How are new core devs inducted

We may be able to write up processes for these things as PEPs (maybe those PEPs will form a kind of constitution). But here’s the catch. I’m going to try and let you all (the current committers) figure it out for yourselves.

Note that there’s still the CoC — if you don’t like that document your only option might be to leave this group voluntarily. Perhaps there are issues to decide like when should someone be kicked out (this could be banning people from python-dev or python-ideas too, since those are also covered by the CoC).

Finally. A reminder that the archives of this list are public (https://mail.python.org/pipermail/python-committers/) although membership is closed (limited to core devs).

I’ll still be here, but I’m trying to let you all figure something out for yourselves. I’m tired, and need a very long break.

Personally speaking, as shown in the examples in this article, the walrus operator can be quite useful and help with some performant operations.

This is to show how even in the open source community, with highly smart people, there are disagreements that go beyond the professional level and get personal.

Projects are hard, designing programming languages is hard and we should thank those who take their time to build the tools we use every day to create awesome things.