Walrus Operator Motivation
00:00 Motivation. In many languages, including C and its derivatives, assignment statements function as expressions. This can be both very powerful and a source of confusing bugs.
For example, the code seen onscreen is valid C, but it doesn’t execute as intended. Here,
if (x = y) will evaluate to
True and the code snippet will print out
"x and y are equal".
Is this the result you were expecting? You were trying to compare
y. How did the value of
x change from
The problem here is that you’re using the assignment operator, a single equal sign (
=), instead of the equality comparison operator, two equal signs (
x = y is an expression that evaluates to the value of
y. In this example,
x = y is evaluated as
8, which is considered
True in the context of the statement.
Take a look at the corresponding example in Python. This code raises a
SyntaxError. Unlike the C example, this Python code gives you an explicit error instead of a bug.
01:15 The distinction between assignment statements and assignment expressions in Python is useful in order to avoid these kinds of hard to find bugs. PEP 572 argued that Python is better suited to having different syntax for assignment statements and expressions, instead of turning the existing assignment statements into expressions.
One design principle underpinning the walrus operator is that there are no identical code contexts where both an assignment statement using the equals operator (
=) and an assignment expression using the colon equals operator (
:=) would be valid. For example, you can’t do a plain assignment with the walrus operator.
02:04 In many cases, you can add parentheses around the assignment expression to make it valid Python.
02:14 Writing a traditional assignment statement with equals is not allowed inside such parentheses. This helps you catch potential bugs.
02:24 In the next section of the course, you’ll see some typical use cases for the walrus operator.
Become a Member to join the conversation.