Loading video player…

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.

00:13 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".

00:28 Is this the result you were expecting? You were trying to compare x and y. How did the value of x change from 3 to 8?

00:37 The problem here is that you’re using the assignment operator, a single equal sign (=), instead of the equality comparison operator, two equal signs (==).

00:48 In C, 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.

01:02 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.

01:38 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.