The Walrus Operator in Python 3.8
Python 3.8 brought about a new assignment expression that trims your length of code and improves readability.
Let me explain how:
The Operator
:=
➡ The walrus operator assigns values to variables as part of a larger expression1.
The use of the walrus operator should be limited to clean cases that reduce complexity and improve readability.
Usage
In this example, the operator helps avoid calling len() twice or defining n outside the loop in vain:
1
2
if (n := len(a)) > 10:
print(f"List is too long ({n} elements, expected <= 10)")
But overall, the main use case for which I’ve been dreaming about the existence of this operator is for list comprehensions:
1
2
[clean_name.title() for name in names
if (clean_name := normalize('NFC', name)) in allowed_names]
Where a value computed in a filtering condition is also needed in the expression body.
Resources
This post is licensed under CC BY 4.0 by the author.