←back to thread

160 points leontrolski | 1 comments | | HN request time: 0s | source
Show context
cpburns2009 ◴[] No.41887804[source]
For all of the syntax features Python has been adding over the years, this would be a nice enhancement: making the "else None" optional in the ternary if-expression. E.g.,

    spam = eggs if bar
    # vs
    spam = eggs if bar else None
replies(3): >>41887917 #>>41887943 #>>41888372 #
TwentyPosts ◴[] No.41887943[source]
Do we really need more syntactic sugar? Frankly, I am still confused why Python is going for a separate syntax for if expressions instead of just making its regular ifs into expressions
replies(2): >>41887952 #>>41888104 #
albertzeyer ◴[] No.41888104[source]
There is an advantage of having this as syntax, which is a difference in semantics, which you couldn't get if this would just be an expression, namely:

    x = func1() if something else func2()
In this example, only func1() or func2() is being called, but not both.
replies(1): >>41888329 #
gray_-_wolf ◴[] No.41888329[source]
I do not understand why

    x = if something:
          func1()
        else:
          func2()
Would not work. At least that is what I imagine when it is said "make if an expression".
replies(2): >>41888529 #>>41888803 #
1. zahlman ◴[] No.41888803{3}[source]
Other languages do this sort of thing, so certainly it "would work". But it's very much counter to the design and aesthetics of Python.

Python is intended to enforce a strong distinction between statements and expressions (`:=` notwithstanding :/) because it sidesteps a lot of questions that one might otherwise ask about how it's intended to be parsed (including by humans).

Being able to write something like your example makes it harder to figure out where the end is, figure out what happens if there's more than one statement inside an `if` (do we only consider the result of the last expression? What if the last thing isn't an expression?), etc. By the time you get to the end of understanding what's happening inside the block, you can lose the context that the result is being assigned to `x`.

At the other extreme, everything is an expression, and you have Lisp with funky syntax. But Python holds that this syntactic structure is important for understanding the code. I sense that this is part of what "Flat is better than nested" is intended to mean.