26

Python 3.8 now has "the walrus operator"

:=

Comments
  • 1
  • 6
    Why are so many languages bringing this relic from Pascal back?
  • 6
    @kescherRant Because it's the only mathematically correct operator for assignment.
    But it does not make too much sense if you do not use "=" for comparison.

    Like everything in Python, this is something put on top of an existing stack of solutions.
  • 2
    It's still gonna suck.
  • 1
    Interesting: https://docs.python.org/3/whatsnew/...

    Apparently the idea is to replace double calls, or intermediary variables. It looks a little strange, but removing variable assignment does help reduce bugs. Which was a driver for comprehensions as well. I think this is an attempt to squash specific classes of bugs that can occur. Also it can help reduce code. Less things to maintain.
  • 1
    Why?

    E.g. for list comprehensions where you would need to repeat stuff in result and in if part.

    Or in normal ifs, to check whether something exists, and assign it in the same line.
  • 2
    I'm still confused on what this does after reading several explanations
  • 1
    More importantly, Python 3.8 has been released
  • 2
    @halfflat

    Python is super edgy. Sometimes it cuts right to the chase, sometimes it cuts right into your developer soul.
  • 3
    @tman540 imagine I need to calculate velocity and ALSO save both deltas. With Walrus it would be something like this:
    ```
    x1 = 1
    x2 = 2
    t1 = 0
    t2 = 3
    v = (dx := (x2 - x1))/(dt := (t2 - t1))
    print("v:", v) # v: 0.3...
    print("DeltaX:", dx) # DeltaX: 1
    print("DeltaT:", dt) # DeltaT: 3
    ```

    Without it, it would become something like this:

    ```
    x1 = 1
    x2 = 2
    t1 = 0
    t2 = 3
    dx = (x2 - x1)
    dt = (t2 - t1)
    v = dx/dt
    print("v:", v) # v: 0.3...
    print("DeltaX:", dx) # DeltaX: 1
    print("DeltaT:", dt) # DeltaT: 3
    ```

    It let's you assign values inside other expressions.
  • 0
    @gitcommit ahh, I think I understand now. Thanks for the explanation!!!
  • 3
    @angrysnekguy I'd take this line or two if my colleagues can understand what I do there.
  • 0
    @gitcommit The only thing I don't understand is, why not just go the JS / PHP route and make assignment have a return value:

    v = (dx = 2-1) / (dt = 4-2)

    Just call it Python 4, it's not like they care about backwards compatibility 🤓 /troll
  • 0
    @bittersweet I think it could be confused with multiple assignment:

    a = b = 1
  • 0
    @gitcommit doesn't matter though, because that would be the same as

    a = (b = 1)
Add Comment