55

Whatever the fuck Python's ternary operator syntax is supposed to be.

Comments
  • 29
    For the uninitiated, ternary syntax in literally any other language is:

    condition ? true_result : false_result

    In Python it's:

    true_result if condition else false_result

    Like goddamn, I get that it's closer to how we'd make such a statement in natural language but from a programming point of view it's awful, if only for the fact that the condition is sandwiched inbetween the results.
  • 17
    Agreed, I like Python in general but this is just awful.
  • 4
    Oh god.

    If there wasn't so strict whitespace rules you could simply:

    if condition: true_result else: false_result
  • 10
    Honestly I think if the rest of the industry did it this way, it would be better. The ternary operator is infamously unreadable. But the Python operator is:

    - Based on math
    - Reads like English

    I actually love it. But it's different from every other goddamn language so I always need to Google it
  • 2
    I do agree that the order is weird. Though it's somewhat better than the default order
  • 2
    it's more like a one liner if-else statement
  • 7
    Suppose you are using in assignment:

    variable = 1 if condition else 2

    instead of:

    variable = condition ? 1 : 2

    I mean, you can clearly see which one is better 🤷🏻‍♂️
  • 2
    @michezio yeah, looks much better because you see the main value first and then the fallback one (well, assuming the common use case for a ternary as a failsafe assignment)
  • 1
    @AlgoRythm
    I respect your opinion, but I think you're wrong.

    Is the Python one based on English? Yes
    Is the "normal" ternary operator difficult to read? Yes
    Can I handle the change, or will my head explode? Change would kill me.

    That's the only argument I have against what you wrote
  • 0
    Meanwhile in Clojure “if” is just

    (if condition true false)
  • 4
    I think it may be because of the usage in comphrehensions:

    list = [x if x%2 == 0 else 10 for x in range(20)]

    print(list)
  • 0
  • 0
    @Demolishun yeah,seems like some sort of consistency here
  • 1
    How is it hard to comprehend simple logic? I don’t see anything wrong with it.

    >> True if True else False
    True

    >> False if not False else True
    False
  • 1
    @amoux because it's more common that the condition is presented before the expression that is run. You might first read it as if true_result is always run because there's no condition before it.
  • 0
    As a person just learning Python I like it. I prefer a language that tries to be more like the spoken word. For me Python seems to be easier to retain as well. I've been through tutorials for C# and JS and I didn't like them near as much. But if I was proficient in another language first I'd probably feel the same way you do.
Add Comment