Getting Started with the Walrus Operator in Python

2020-12-20

What is the Walrus Operator

The walrus operator is a new assignment operator := introduced in Python 3. Its main purpose is to save lines of code, but can also help with performance.

Example

To illustrate its use, let's start with an example. Let's say we want to check if an environment variable is set.

env_base = os.environ.get("EMAIL_SERVER", None)
if env_base:
    return env_base

This pattern is common. We initialize a variable, then we check if the variable evaluates to true. With the walrus operation, we can remove a line.

if env_base := os.environ.get("EMAIL_SERVER", None):
    return env_base

Example 2

For another example, lets say we ware reading the contents of a file. It is common to loop over a file, but start by checking if the first line is not empty.

line = f.readline()
while line:
    do_something(line)
    line = f.readline()

We can use the walrus operator again to simplify this.

while line := f.readline():
    do_something(line)

Conclusion

That's it for our quick tip on the Walrus operator. If you want to read more, check out the official PEP standard: https://www.python.org/dev/peps/pep-0572/.

GoTea - KoalaTea