←back to thread

160 points leontrolski | 6 comments | | HN request time: 1.119s | source | bottom
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 #
1. genter ◴[] No.41887917[source]
So if "else None" is omitted, if bar is false, then does spam == None or is it unmodified? The former is what I think you want, but that would be very confusing.
replies(2): >>41888248 #>>41889001 #
2. 333c ◴[] No.41888248[source]
Yeah, it would be confusing. In Ruby, this would leave spam unmodified.
replies(1): >>41888731 #
3. 8n4vidtmkvmk ◴[] No.41888731[source]
That's even more confusing. There's an =, I expect an assignment to happen. Maybe we just leave this one alone.
replies(2): >>41889326 #>>41889718 #
4. trehalose ◴[] No.41889326{3}[source]
Perhaps using a parenthesized assignment expression with the walrus operator would be unambiguous:

(spam := eggs) if bar

I think that seems reasonable? It would act just the same as it already does with an explicit `else None`, if I'm not mistaken. I don't find it beautiful though.

5. 333c ◴[] No.41889718{3}[source]
In Ruby, the `if [condition]` modifier at the end of a line is used for more cases than just assignment. For example, `return if s.blank?` and `raise "invalid" if input.length > 100`. In Ruby, this pattern makes it clear that the statement is only executed if the condition is met.

I'm not advocating for this feature to be added to Python, just explaining why it's not confusing in Ruby.

replies(1): >>41889944 #
6. mypalmike ◴[] No.41889944{4}[source]
Though I used it for 2 years of it as my primary language at work, I never quite got used to Ruby's quirky idioms like this. It just reads badly to me, in terms of quickly understanding code flow, to have statements that start with "raise" or "return" which might not raise or return. Similar to the up-thread comment about assignment.