在Python中使用赋值表达式时如何完成赋值语句"x = y := f(x)"?

How can an assignment statement "x = y := f(x)" be done when using assignment expressions in Python?

我读了in Twitter:

#Python news: Guido accepted PEP 572. Python now has assignment expressions.

 if (match := (pattern.search) pattern.search(data)) is not None:
    print((match.group) mo.group(1))

 filtered_data = [y for x in data if (y := f(x)) is not None]

(correction mine in the 2nd line of code)

如图所示,PEP 572 -- Assignment Expressions describes this to be present in Python 3.8:

This is a proposal for creating a way to assign to variables within an expression using the notation NAME := expr.

我已经仔细阅读了描述和示例,我发现这是避免重复调用或赋值的便捷方法,所以不是:

match1 = pattern1.match(data)
match2 = pattern2.match(data)
if match1:
    return match1.group(1)
elif match2:
    return match2.group(2)

或效率更高的:

match1 = pattern1.match(data)
if match1:
    return match1.group(1)
else:
    match2 = pattern2.match(data)
    if match2:
        return match2.group(2)

现在可以说:

if match1 := pattern1.match(data):
    return match1.group(1)
elif match2 := pattern2.match(data):
    return match2.group(2)

同样,现在可以说:

if any(len(longline := line) >= 100 for line in lines):
    print("Extremely long line:", longline)

但是,我不明白 PEP 中给出的这个例子是无效的:

y0 = y1 := f(x)  # INVALID

y0 = (y1 := f(x)) 是否正确?怎么用?

那些想知道它在哪里可用的脚注:我已经安装了 Python 3.7 and it does not work there, since the PEP currently shows as "Status: Draft". However, the PEP talks about Proof of concept / reference implementation (https://github.com/Rosuav/cpython/tree/assignment-expressions),所以这是使用他们的 Python 3.8 alpha 0 版本的问题,其中包括它.

作为 PEP 中的 explicitly stated

Unparenthesized assignment expressions are prohibited at the top level in the right hand side of an assignment statement; for example, the following is not allowed:

y0 = y1 := f(x)  # INVALID

Again, this rule is included to avoid two visually similar ways of saying the same thing.

later,

As follows from section "Exceptional cases" above, it is never allowed at the same level as =. In case a different grouping is desired, parentheses should be used.

...

# INVALID
x = y := 0

# Valid alternative
x = (y := 0)