python - 为什么海象行动不是一个有效的陈述?

标签 python terminal walrus-operator

我在终端中执行一些 python 操作,当时我编写了 x := 1 并且它显示了语法错误。

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

我知道海象运算符是一个表达式,但其他表达式也可以完美工作。

>>> 5 + 3 - 1
7 

甚至海象运算也在括号内进行。

>>> (x := 1)
1

所以我的问题是,为什么其他所有表达式都可以作为语句,而 walrus 则不然?

最佳答案

来自 PEP 572,"Exceptional cases" (强调我的):

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

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.

在语法中排除裸赋值表达式很简单。如果仅禁止某些带括号的表达式(即包含赋值表达式的表达式),同时仍然允许其他表达式,则会变得更加复杂,这就是为什么 (y := f(x)) 有效。

关于python - 为什么海象行动不是一个有效的陈述?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69465586/

相关文章:

linux - SSH 访问没有终端的 ubuntu box

linux - 如何自动打开带有命令的拆分终端

python - 为什么在成员变量上使用 walrus 运算符会引发 SyntaxError?

python - 赋值表达式的求值顺序(海象运算符)

python - 创建表示二进制值的字符串列表,具有固定长度

python - 在 Pandas 中解析 JSON

plot - 使用 gnuplot 创建数据文件

python - 如何在 f 字符串中解释命名表达式?

python - 如何修复 PyModbus 无法通过 IME 使用 IF96015 接口(interface)解码响应错误

python - Django Rest 框架 : Register multiple serializers in ViewSet