←back to thread

317 points est | 6 comments | | HN request time: 0.838s | source | bottom
Show context
oooooof ◴[] No.17448560[source]
What is it? The link points to a discussion more deep than I’m willing to read.
replies(10): >>17448567 #>>17448570 #>>17448571 #>>17448572 #>>17448575 #>>17448579 #>>17448584 #>>17448591 #>>17448617 #>>17448638 #
1. OskarS ◴[] No.17448617[source]
Basically it's about adding := as an "assignment expression operator", that does assignment and returns the value as an expression. That is, take this regex example:

    match1 = re1.match(text)

    if match1 is not None:
        do_stuff()
    else:
        match2 = re2.match(text)

        if match2 is not None:
            do_other_stuff()
Which is a bit clunky. you only want to evaluate match2 in case match1 fails, but that means a new level of nesting. Instead, with this proposal, you could do this:

    if (match1 := re1.match(text)) is not None:
        do_stuff();
    elif (match2 := re2.match(text)) is not None:
        do_other_stuff()
Evaluate and assign in the if-statement itself. This is not dissimilar to the equals operator in C. In C, you would frequently find loops like `while ((c = read()) != EOF) { ... }`. This would presumably allow a similar pattern in python as well.

More information can be found in PEP-572: https://www.python.org/dev/peps/pep-0572/

replies(1): >>17448750 #
2. oblio ◴[] No.17448750[source]
Hehe. More chances for C-style bugs like:

if (a = b) /* Oooops, meant a == b! */

replies(4): >>17448889 #>>17448893 #>>17448905 #>>17453446 #
3. toxik ◴[] No.17448889[source]
Difference is bigger, C is `if (a = b)` vs `if (a == b)`. Python is `if (a := b)` vs `if a == b`
4. afraca ◴[] No.17448893[source]
Except it's more likely you're accidentally inserting a character twice than inserting another extra character (':')
5. MaxBarraclough ◴[] No.17448905[source]
Presumably that's why they've gone with the far more sensible ":=" syntax.

The use of "=" for assignment has long been a pet peeve of mine. It was a mistake when C did it, and it's been a mistake for so many subsequent languages to copy it.

"=" shouldn't be an operator at all, it makes a lot more sense to use ":=" and "==".

Pascal's use of ":=" for assignment and "=" for equality, strikes me as almost as clear.

Still, at least C makes consistent use of '=' for assignment, unlike that god-forsaken trainwreck of a language, VB.Net, which uses it for both assignment and for equality depending on context.

6. bluecalm ◴[] No.17453446[source]
It's not a problem in C anymore as modern compilers warn about that so you had to put additional parenthesis to make it clearer.

I like C way of assignment being an expression. I think having separate statement and then assignment expresdion is a mess. It's still useful though as Python was missing where keyword like feature from Haskell which is necessary to avoid duplicating computation in list comprehension.