top | item 21862462

(no title)

Luyt | 6 years ago

A while ago, I was also sceptical about the walrus operator, although I use assignments in expressions all the time in C++. But when I was perusing a library written Python the other day, I found five spots in which the walrus operator would make sense - eliminating one line of source code without readability suffering from it.

discuss

order

bakery2k|6 years ago

Is saving 5 lines of code really worth breaking Python's "one way to do it" design principle?

masklinn|6 years ago

Python's principle is not an has never been "one way to do it". Python's principle is:

> There should be one — and preferably only one — obvious way to do it.

Which is a very, very different assertion. And there remains one — and exactly only one — obvious way to do an assignment, because the walrus operator is literally invalid syntax as a statement:

    >>> [a:=1]
    [1]
    >>> a:=1
      File "<stdin>", line 1
        a:=1
         ^
    SyntaxError: invalid syntax

CallocRoast|6 years ago

That principle was bullshit anyway. There have always been multiple ways to do things, the one way was just whatever the elder Pythonista deemed to be pythonic that day.

dr_zoidberg|6 years ago

In my work we have code in many places along the lines of:

    data = expensive_function(blah, blah_blah)
    if data:
        # many lines of processing
        data = expensive_function(blah, blah_bah)
And seen a lot of times where newcomers forget the assingment at the end that makes everything move. So yeah, the walrus version would be a lot simpler:

    while data := expensive_function(blah, blah_blah):
        # process data
This is just one of the "edge cases" where the walrus makes sense.

pwdisswordfish2|6 years ago

Yes. That principle was quite silly to begin with.