Python 3.8 will introduce Assignment Expressions.
It is a new symbol: :=
that allows assignment in (among other things) comprehensions. This new operator is also known as the walrus operator.
It will introduce a lot of potential savings w.r.t. computation/memory, as can be seen from the following snippet of the above linked PEP (formatting adapted for SO):
Syntax and semantics
In most contexts where arbitrary Python expressions can be used, a
named expression can appear. This is of the form NAME := expr
where
expr
is any valid Python expression other than an unparenthesized
tuple, and NAME
is an identifier.
The value of such a named expression is the same as the incorporated
expression, with the additional side-effect that the target is
assigned that value:
Handle a matched regex
if (match := pattern.search(data)) is not None:
# Do something with match
A loop that can't be trivially rewritten using 2-arg iter()
while chunk := file.read(8192):
process(chunk)
Reuse a value that's expensive to compute
[y := f(x), y**2, y**3]
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]
This is already available in the recently releases alpha version (not recommended for production systems!). You can find the release schedule for Python 3.8 here.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…