Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Assignment Expression Syntax

00:00 Walrus operator syntax. One of the main reasons assignments were not expressions in Python from the beginning is the visual likeness of the assignment operator (=) and the equality comparison operator (==). This could potentially lead to bugs.

00:18 When introducing assignment expressions, a great deal of thought was put into how to avoid similar bugs with the walrus operator. As mentioned previously, one important feature is the walrus operator is never allowed as a direct replacement for the assignment operator, and vice versa.

00:35 As you saw at the beginning of the course, you can’t use a plain assignment expression to assign a value. It is syntactically legal to use an assignment expression to only assign a value, but only if you add parentheses.

00:57 Even though this is possible, this really is a prime example of where you should stay away from the walrus operator and use a traditional assignment statement instead.

01:07 There are several other examples where the walrus operator is either illegal or discouraged. All of these examples raise a SyntaxError.

01:40 In all of these cases, you would be better served using the assignment operator instead. The next examples are all similar and they are all legal code. However, the walrus operator doesn’t improve your code in any of these cases.

02:20 None of these examples make your code more readable. You should instead do the extra assignment separately by using a traditional assignment statement. If you want to look at this in more depth, take a look at the original PEP which created the assignment expression operator.

02:39 There’s one use case where the := character sequence is already valid Python. In f-strings, a colon (:) is used to separate values from their format specification.

02:56 The := in this case does look like a walrus operator, but the effect is quite different. To interpret x:=8 inside the f-string, the expression is broken into three parts: the x, the colon (:), and the =8. Here, x is a value, the colon (:) acts as a separator, and =8 is a format specification.

03:21 In this context, equals (=) specifies an alignment option. In this case, the value is padded with spaces in a field width of 8.

03:31 To use assignment expressions inside f-strings, you need to add parentheses.

03:44 This updates the value of x as expected. However, you’re probably better off using traditional assignments outside of your f-strings instead.

03:55 Let’s look at some other situations where assignment expressions are illegal. Attribute and item assignment: You can only assign to simple names, not dotted or index names.

04:22 As you can see, this fails with a descriptive error message, and there’s no straightforward workaround. Iterable unpacking: You can’t unpack when using the walrus operator.

04:45 Augmented assignment: You can’t use the walrus operator combined with augmented assignment operators like plus equals (+=). This raises a SyntaxError.

05:01 The easiest workaround here would be to do the augmentation explicitly. When you’re using the walrus operator, it will behave similarly to traditional assignment statements in many respects.

05:14 The scope of the assignment target is the same as for assignments. It will follow the LEGB rule. Typically, the assignment will happen in the local scope, but if the target name is already declared global or non-local, that is honored.

05:33 For more information on this topic, check out this Real Python course, Python Scope & the LEGB Rule: Resolving Names in Your Code. The precedence of the walrus operator can cause some confusion.

05:47 It binds less tightly than all other operators except the comma, so you might need parentheses to delimit the expression that’s assigned. As an example, note what happens when you don’t use parentheses.

06:12 Here, square is bound to the whole expression number ** 2 > 5. In other words, square gets the value True and not the value of number ** 2, which was the intention. In this case, you can delimit the expression with parentheses.

06:38 The parentheses make the if statement both clearer and actually correct. There’s one final gotcha. When assigning a tuple using the walrus operator, you always need to use parentheses around the tuple.

06:53 Compare the following assignments.

07:21 Note that in the second example, walrus takes the value 3.8 and not the whole tuple of (3.8, True). That’s because the walrus operator binds more tightly than the comma.

07:33 This may seem a bit annoying. However, if the walrus operator bound less tightly than the comma, it wouldn’t be possible to use the walrus operator in function calls with more than one argument.

07:45 The style recommendations for the walrus operator are mostly the same as for the assignment operator. First, always add spaces around the walrus operator in your code.

07:57 Second, use parentheses around the expression as necessary but avoid adding extra parentheses that are not needed. The general design of assignment expressions is to make them easy to use when they’re helpful but to avoid overusing them when they might clutter up your code.

08:15 Next up, a look at some of the pitfalls that may meet you when you use the walrus operator.

Avatar image for dar3232

dar3232 on May 5, 2023

I took a step further the unpacking example… 🤯

>>> x1 = (a, b, c := 2)
>>> x1
(2, 2, 2)
>>> a
2
>>> b
2
>>> c
2
>>> x2 = (a, b, c := 2, 3, 4)
>>> x2
(2, 2, 2, 3, 4)
>>> a
2
>>> b
2
>>> c
2

Become a Member to join the conversation.