Python 解释器中的海象运算符

Walrus operator in Python interpreter

当我在 Python(3.9.6) 中使用如下海象运算符时 口译员,

>>> walrus:=True

我收到一个语法错误:

  File "<stdin>", line 1
    walrus := True
                  ^
SyntaxError: invalid syntax

这与下面的有何不同?

>>> print(walrus := True)

这是不同的,因为 Python 核心开发人员 非常 对违反 the Zen of Python 准则“应该有一个 - 最好只有一个 -显而易见的方法”,并选择在不向表达式添加额外括号的情况下将普通 = 的大多数用法替换为 := 不方便。

而不是允许 := 在所有上下文中替换 =they specifically prohibited 未加括号 top-level 海象的使用:

Unparenthesized assignment expressions are prohibited at the top level of an expression statement.

y := f(x)  # INVALID
(y := f(x))  # Valid, though not recommended

This rule is included to simplify the choice for the user between an assignment statement and an assignment expression – there is no syntactic position where both are valid.

在许多禁止 := 的情况下,您可以通过在表达式周围添加不​​必要的括号使其有效,因此:

(walrus:=True)

工作得很好,但假设大多数人会坚持更简单和更多的东西,这已经够痛苦的了 Pythonic:

walrus = True

在那种情况下。