Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do Assignment Expressions `:=` work in Python?

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.)

like image 888
Benoît P Avatar asked Feb 05 '19 23:02

Benoît P


People also ask

How do you use an assignment statement in Python?

We use Python assignment statements to assign objects to names. The target of an assignment statement is written on the left side of the equal sign (=), and the object on the right can be an arbitrary expression that computes an object. Assignment creates object references instead of copying the objects.

Why can't I use an assignment in an expression in Python?

The error is a simple typo: x = 0, which assigns 0 to the variable x, was written while the comparison x == 0 is certainly what was intended.

How do you assign an expression to a variable in Python?

Python 3.8, released in October 2019, adds assignment expressions to Python via the := syntax. The assignment expression syntax is also sometimes called “the walrus operator” because := vaguely resembles a walrus with tusks. Assignment expressions allow variable assignments to occur inside of larger expressions.

Is assignment a statement or expression in Python?

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.


1 Answers

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))
like image 81
Benoît P Avatar answered Sep 27 '22 23:09

Benoît P