←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 #
__mharrison__ ◴[] No.41888529{3}[source]
This doesn't work because the if statement is a statement. Statements don't evaluate to anything in Python, so you can't assign it to x.
replies(1): >>41888718 #
8n4vidtmkvmk ◴[] No.41888718{4}[source]
Hence "make it an expression"
replies(1): >>41889031 #
1. otabdeveloper4 ◴[] No.41889031{5}[source]
It's way to late to fix the "statement vs expression" bug in Python's design.

We could have done that in the v3 switch, but we decided to spend man-centuries of effort on chasing already deprecated legacy Windows Unicode semantics instead.