Hacker News new | ask | show | jobs
by bakery2k 2364 days ago
Is saving 5 lines of code really worth breaking Python's "one way to do it" design principle?
4 comments

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
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.
Not true. The language optimizes for the way it is intended to be used, and changes remain sensitive to those optimizations.

"Pythonic" means intended usage, and "unPythonic" is shorthand for "you found another way to do it that kinda does what you want but (is ten times as slow/takes up ten times as much memory/doesn't work for edge-cases/has more unintentional side-effects) because it wasn't the intended usage, which is fine for your own personal projects, but please don't bring that into my code base, and pretty please don't teach other people to do it that way..."

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.
Yes. That principle was quite silly to begin with.