赋值表达式`:=` 在 Python 中是如何工作的? [英] How do Assignment Expressions `:=` work in Python?

查看:78
本文介绍了赋值表达式`:=` 在 Python 中是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了关于赋值表达式的 PEP 572 并且我发现了这个代码是我可以使用它的清晰示例:

while line := fp.readline():do_stuff(行)

但我很困惑,从我读到的内容来看,它应该像正常赋值一样工作,但返回值.但它似乎不像那样工作:

<预><代码>>>>w:=1文件<stdin>",第 1 行w:=1^语法错误:无效语法

现在经过修改后,我意识到了以下工作:

<预><代码>>>>(w:=1)1

但它感觉如此不Pythonic.它是唯一需要括号的运算符:

<预><代码>>>>w = 1>>>w + w2>>>w == w真的>>>w 是 w真的>>><瓦错误的

解析器是否有理由将它与 Python 中的其他任何东西区别对待......?我觉得我错过了一些东西.这不仅仅是一个运算符.

在 REPL 中使用 := 来分配变量会非常有用,因为值将被显示.

<小时>

(更新:我不鼓励就这个敏感话题进行自以为是的讨论.请避免发布有用的评论或答案.)

解决方案

正如 GreenCloakGuy 所提到的,它是否有避免混淆,如此处所说,我认为这一行总结了一切:

<块引用>

不存在 = 和 := 都有效的语法位置.

这也让这些事情变得无效,因为太混乱了:

y0 = y1 := f(x)foo(x = y := f(x))

I've read PEP 572 about assignment expressions and I found this code to be a clear example where I could use it:

while line := fp.readline():
    do_stuff(line)

But I am confused, from what I read, it is supposed to work just like normal assignment but return the value. But it doesn't appear to work like that:

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

Now after tinkering with it I realised the following works:

>>> (w:=1)
1

But it feels so unpythonic. It is the only operator that requires parentheses:

>>> w = 1
>>> w + w
2
>>> w == w
True
>>> w is w
True
>>> w < w
False

Is there a reason for it to be treated by the parser differently than literally anything else in Python...? I feel like I am missing something. This is not just an operator.

It would be super useful to use := in the REPL to assign variables as the value would be displayed.


(Update: I do not encourage opinionated discussion on this sensitive topic. Please avoid posting comments or answers other than useful ones.)

解决方案

As GreenCloakGuy mentioned, it is there to avoid confusion, as said here, I think this line sums it all:

there is no syntactic position where both = and := are valid.

It also makes things like these invalid because too confusing:

y0 = y1 := f(x)
foo(x = y := f(x))

这篇关于赋值表达式`:=` 在 Python 中是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆