This is the 8th day of my participation in the August More text Challenge. For details, see: August More Text Challenge

1. Introduction

Python 3.8 introduces a new feature described in PEP 572 — assignment expressions, implemented by Emily Morehouse. Yeah, that’s the girl down there.


2. Grammar and semantics

Assignment Expressions, which is the official official name used in the PEP 572 heading, Assignment Expressions in English. It’s also called a Named expression, Named Expressions. The new operator it involves := is affectionately known as the Walrus operator, because the colon: a pair of small eyes like a walrus, and the equal sign = is a pair of tusks like a walrus.

The syntax for an assignment expression is NAME := expr, which, as the NAME suggests, does two operations:

  • Computed expressionexprThe results of the
  • Assign the result to the nameNAMEThe variables of

Note:

  • In mostPythonAssignment expressions can be used in any context in which expressions can occur. Some exceptions are inPEP 572The general rule is not to use assignment expressions when they are unnecessary or when they affect the readability of the code.
  • The variable nameNAMEIs a validPythonIdentifiers, expressionsexprCan be anything legal except a tuple without parenthesesPythonExpression.
  • Assign the value of an expression and the expression it containsexprIs the same as the value of, and is also assigned toNAME.

3. Effects and cases

Let’s start with the simplest one:

>>> walrus = False
>>> print(walrus)
False
>>> print(walrus := True)
True
>>> walrus
True
Copy the code

Print (walrus := True) one sentence and do two sentences work:

  • walrus = True
  • print(walrus)

Do you want to write print(walrus = True)? Not in Python:

>>> print(walrus = True)
Traceback (most recent call last):
  File "<stdin>", line 1.in <module>
TypeError: 'walrus' is an invalid keyword argument for print(a)Copy the code

You know the assignment expression and the walrus operator, which compresses the amount of code, which compresses the line. This will add a lot of lines to the Python solution, which was not possible before.

Specifically, walrus operators are often used to give names to conditional expressions that need to be used later, such as an if statement or an expression following a while statement. That’s a little bit unintuitive, but let’s do one more example.

We want to match ‘app’ from scratch in the string ‘apple’, and then output what matches. We can generally do this:

>>> import re
>>> m = re.match(r'app'.'apple')
>>> if m is not None:
.    print('Match :', m) ... Match: < re.matchobject; span=(0.3), match='app'>
Copy the code

With the walrus operator, you can press the line, but you can write it like this:

>>> import re
>>> if (m := re.match(r'app'.'apple')) is not None:
.    print('Match :', m) ... Match: < re.matchobject; span=(0.3), match='app'>
Copy the code

(m := re.match(r’app’, ‘apple’));

if m := (re.match(r'app'.'apple') is not None):
    ...
Copy the code

So if m is True, it’s not the Match object we want.

Here’s another example for a while loop:

>>> while (s := input('Say something:')) != 'q':
.    print('You entered:'+ s) ... Say something: Hello, you type: Hello, say something: world, you type: world, say something: qCopy the code

The above code continuously reads user input and prints it without ‘q’. If you don’t use the walrus operator, you need to write:

>>> while 1:
.    s = input('Say something:')
.    if s == 'q':
.        break
.    print('You entered:'+ s) ... Say something: Hello, you type: Hello, say something: world, you type: world, say something: qCopy the code

The walrus operator, by contrast, compresses more than just one line or two. (I counted them carefully. Yes, three lines were compressed.)

In addition, walrus operators can reuse computatively expensive values:

# Reuse a value that's expensive to compute
[y := f(x), y**2, y**3]
Copy the code

Or share a subexpression in the filter clause of a list derivation, which is actually an example of what we use after an if:

# Share a subexpression between a comprehension filter clause and its output
filtered_data = [y for x in data if (y := f(x)) is not None]
Copy the code

See PEP 572 for more information about the walrus operator usage and precautions, and be sure not to impair code readability for sheer show-off. Walrus is good, but don’t use it blind!


4. Relevant information

  • PEP 572
  • Assignment Expressions: The Walrus Operator
  • Try out walrus operator in Python 3.8