Python Forum

Full Version: Python 3.8 :=
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Since Python 3.8 allows one to combine assignment with a condition like:
if (x:=f()) == 1:
print("function returned 1")
Is there any reason in Python 3.8 or greater, to use assignment with =. I think that we should always use := in new code.

Most of you know that the following is valid in Java and C/C++ if ( ((x=f()) == 1)

And Algol used := for assignment to make sure that no one confused assignment and test for equality
PEP 572 Wrote:Unparenthesized assignment expressions are prohibited at the top level of an expression statement.

So it looks like y := x would fail by itself. And Python already distinguishes between assignment (=) and equality checks (==).
(Dec-22-2019, 02:02 AM)ichabod801 Wrote: [ -> ]So it looks like y := x would fail by itself.

Yep, it is so:

>>> x := 5
  File "<stdin>", line 1
    x := 5
      ^
SyntaxError: invalid syntax
>>> (x := 5)
5
I prefer to use assignment expressionn in cases where it actually shortens the code, avoids calculation of same value and makes it more concise.

Example of calculating once (minimum number of page flips to location starting either from beginning or end):

min(from_start := location // 2, total_pages // 2 - from_start)
Hello there. I think I was given inaccurate answers.

I know that
:= does not work in Python 3.7!
My question dealt with a new Python feature.

Python 3.8, released in October of this year introduced :=

Please read from "What's New":
Summary – Release highlights
New Features
Assignment expressions
There is new syntax := that assigns values to variables as part of a larger expression. It is affectionately known as “the walrus operator” due to its resemblance to the eyes and tusks of a walrus.

In this example, the assignment expression helps avoid calling len() twice:

if (n := len(a)) > 10:
print(f"List is too long ({n} elements, expected <= 10)")

...
Yeah, that's exactly what we are talking about.