The Python Walrus Operator
Posted
Python is my go-to interpreted language. Generally speaking, I have little negative to say about it that has not already been said a million times over. One big thing that I have been missing in python though has recently been introduced in python 3.8. The walrus operator, so called because the notation :=
looks like a walrus is formally called “assignment expressions” and was introduced by PEP 572. It allows you to assign a variable within an expression. For example, we can use it to do something like:
a = [1,2,3]
if (b := a[2]) < 5:
print(b)
Before we would have needed to do either
a = [1,2,3]
b = a[2]
if b < 5:
print(b)
Or
a = [1,2,3]
if a[2] < 5:
print(a[2])
This feature has long been a part of other languages like php and javascript, in both of which this feature is implemented in such a way that using it is often considered bad practice. PHP was the first language where I encountered this type of construct, and I impressed by how much more concise it could make code when it was used well. But PHP just uses =
instead of something more deliberate like :=
. Using a single equal sign can lead to bugs where the developer intended to check equality with a ==
or a ===
but only typed =
. By using :=
python avoids this pitfall as a developer is less likely to mistakenly type this new construct, than to miss that second equal sign.