[Python Tips] The New Walrus Operator

Walrus Operator

The Walrus Operator is a new assignment operator announced in Python 3.8 that looks like a walrus.

The walrus operator is used to simplify code when you need an expression while storing the result for future use. This is a common scenario when you need to output the result to a log file.

Example

a = 10
b = 30

if (sum := a + b) > 30:
  print(f"The total is {sum}")

Without the walrus operator, you would need to use code similar to this:

a = 10
b = 30

sum = a+b
if (a + b) > 30:
  print(f"The total is {sum}")

Like most new features, the walrus operator is only syntactic sugar. Syntactic sugar is when a feature is added to make it easier to express something you could already accomplish using the existing feature set. These changes help make code more readable and manageable.

The walrus operator isn't a game-changer but it does help make code more readable and allows you to accomplish more with fewer lines of code without making code unreadable.

Warning

The walrus operator does require Python 3.8 which not all packages will fully support yet. It may take a couple of days or even weeks for most packages to work out any issues with Python 3.8 so your mileage may vary.

I do recommend running at least Python 3.7.4 in the meantime as there has been numerous security updates. These security updates have been rolled up into 3.6.9 as 3.6 brach is in security fix mode only.

If you haven't seen any of my previous Python series, I highly recommend checking them out below:

My Python Tips Series

H2
H3
H4
3 columns
2 columns
1 column
24 Comments
Ecency