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.)
while line := fp.readline():
is also non-sense. It can be simply replaced by a more pythonic wayfor line in fp.readline():
or evenfor line in fp:
.