Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python 3.8 :=
#1
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
Reply
#2
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 (==).
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
(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)
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#4
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)")

...
Reply
#5
Yeah, that's exactly what we are talking about.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020