by ohazi · 5y ago · 0 comments
Because the Python ternary operator is fucking backwards! Why on earth would you put the condition in the middle!?
x = 4 if condition() else 5
vs.: condition() ? 4 : 5
vs. the author's own lisp example: (setq x (if (condition) 4 5))
I love ternary operators, and Lisp/ML-style if else blocks that return things, but Python puts the 4 and the 5 so far away from each other that even I hate using it, especially when condition is a chained mess rather than just a function call. a = [1,2,3]
# list comprehension with if
[ x for x in a if x > 1]
[2, 3]
# list comprehension with if/else
[ x if x > 1 else x*2 for x in a]
[2, 2, 3]
When it's just "if" it goes after the "for", when it's "if/else" it goes, all of it, before. I still don't understand why it's this way, it doesn't even make sense even reading it in natural language. I much prefer the mathematical-like syntax present in Scala for this.Edit: Thanks for the responses, they are are insightful, never thought of this that way.
Still in my head the lack of "else" clause implies filtering no matter where, while its presence implies transformation no matter where. The first element of the list is always transformed (though in this example it's identity).
I think it's a case of Python trying to do too much with too little. Personally for anything relatively complicated I still prefer to use filter() and map() as list comprehensions can get unwieldly quick.
In your case you were conditionally choosing a manipulated return value for x and didn't care at all about filtering the list. Here's one with both:
[x if x > y else x*2 for x in a if x % 2 == 0]
^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^
return x as... filter down to only...
x or x*2 even 'x's
There's not really a semantically logical place for an "else" in the latter half because it's only looking for a true statement so it can return x (or not).For example this makes sense:
... if x % 2 == 0 or x == 3
(filter the list to even values of x or the value 3)but this does not:
... if x % 2 == 0 else x == 3
(filter the list to even values, otherwise wait, otherwise?)The problem is that functional-style fails to separate essential bits and fails to give strong visual clues where each bits begins and ends.
That is why the old imperative style is clearer. Compare:
for i in container:
do something with i
and [do something with i for i in container]
One has a clear separation of loop and action, the other requires scanning for the "for i" in the middle. This generalize to other similar construct, and the Python ternary operator has the same flaw. The imperative if / else version clearly separate alternatives on separate lines.IMO, syntax design should always try to learn from the imperative style and always strive to produce a syntax that clearly separate each logical item in a compound statement, and using different lines is one of the best for us human to visually grok.
(That's why even Lisper will often format their code to separate bits on different lines!)
OP clearly stated he didn't understand it:
> When it's just "if" it goes after the "for", when it's "if/else" it goes, all of it, before. I still don't understand why it's this way
and discussing it here on HN shouldn't be punished.
...
Back to the topic at hand ...
List comprehensions save you enough syntax to be worth it, IMHO:
mylist=[]
for i in container:
if i > 10:
mylist.append(i*2)
vs mylist = [x*2 for x in container if x > 10]
... That's a very terse, clean request for work and arguably it's easier to read than "for(int i=0; i<10; i++)", which we've all acclimated to by the end of CS101. I think they're quite worth the trade-off. >>> list([ x if x > 1 else x*2 for x in a if x <3] )
[2, 4]I feel you. I still use them though because they are still more readable then alternatives.
def foo(things: Optional[List[str]] = None) -> None:
thing_list = things if things else []
...I don't like it much, but it's neat that the "happy" path value is a prefix of the assignment statement, i.e. in
x = 4 if thing() else -1
there is a prefix x = 4
which, if the predicate is "expected," is like saying x = value (... unless blah blah)
which, I could see some people liking (maybe Dutch people).Let's just write everything in Scheme for God's sake JOIN US.
> x = value (... unless blah blah)
Except it's the opposite of that, because "if" is the opposite of "unless". It's more like saying
x = value (... if blah blah) x = value (... unless this isn't true, then it's blah instead)
The stuff in parentheses is a caveat. Works just as well your way, and more directly. x = value (... so long as this is true, otherwise blah)I’ve never figured out those question marks. And in your example, what the hell even happens if condition is true or false? At least the lisp version has a function call that includes the word set, so you can kinda guess that the x variable is set.
The if-expression reads very close to English, so you don’t need to look it up in the manual to read it.
I wouldn’t even know what to query to look up `code ? Code : code` in a manual / google. `setq` is also easy to look up.
The question mark colon loses on all counts in my book. I hate it.
It should be:
x = condition() ? 4 : 5 x = ( 1/y if y > 0 else
-1/y if y < 0 else
nan())
idiom.Use umbrella if raining, else wear shades.
Personally I prefer FORTH, which like Yoda reads, and unambiguously puts the condition first, the IF second, the ELSE third, and the THEN last.
FORTH ?KNOW IF
HONK!
ELSE
FORTH LEARN!
THEN
FORTH doesn't have expressions, parens, precedence, or associativity rules, it just has a stack (or rather, two stacks: operand and return; or three of you count the vocabulary search stack). ( And actually it does have parens, but they are for comments! )Personally, from a syntax point of view, as opposed to an easy availability point of view, I prefer Haskell, or Lisp if you can live with the parentheses. Haskell has some syntactic oddities, and the support for infix operators has encouraged the ecosystem to define way too many obscure </?$+/>-looking things, but the syntax mostly just gets out of your way and is relatively regular.
I do admit that if you're going to be infixy anyway, a C-like "?:" ternary is nice. C got its expressions right.
It is, of course, objectively true that one of the things Python does get right about syntax is the significant whitespace, and Haskell has that too (without the stupid colons). Curly braces are the work of the Devil, and "BEGIN" and "END" are just unmentionable.
Haskell got it right.
For data science stuff: Julia
Ternary expressions on one line require branch coverage to be enabled in your e.g. pytest; otherwise it'll look like the whole line is covered by tests when each branch on said line hasn't actually been tested.
.get() -> Union[None, T] x = 5
x = 4 if condition()For readability.
x = condition() and 4 or 5 x = condition() and [] or True
is not equivalent to x = [] if condition() else True
Now, I have seen a genuine application of `X and A or B` before. That occurs when you're checking a condition before, say, popping from a list -- but if the list is empty, you still want a default value.Try it out. https://ideone.com/GciAs8
c = condA ? valA :
condB ? valB :
defaultVal;PHP in all its glory and splendor actually originally used left-to-right instead of right-to-left associativity for the ternary ?: operator, so that expression you wrote works differently in PHP and (JavaScript or C or any other language). (Side note: notice how I used parens instead of depending on you guessing about the relative precedence of "and" and "or" in English.)
It's easy (and perfectly valid) to blame the designers of PHP for not knowing or caring or paying much attention to the syntax of the programming languages they were imitating, and doing something that stunningly stupid, but it just goes to prove that many people (especially PHP designers like Rasmus "I don't care about this crap at all" Lerdorf and typical PHP programmers) don't even have the faintest idea what the precedence and associativity of many of their favorite programming language's operators are, or what those terms even mean, and they just willy nilly cargo cult copy and paste and translate between PHP and JavaScript code examples from Stackoverflow, introducing terrible hard-to-spot bugs.
https://en.wikiquote.org/wiki/Rasmus_Lerdorf
>"We have things like protected properties. We have abstract methods. We have all this stuff that your computer science teacher told you you should be using. I don't care about this crap at all." -Rasmus Lerdorf
But the real fault lies not just with PHP for parroting C incorrectly, but with C for doing something that stupid and hard to remember and easy to get wrong in the first place.
Please always use parens for that kind of stuff, because even if YOU memorized and love to depend on and show off your knowledge of the precedence and associativity rules of the language you're using, the people reading and modifying and maintaining your code probably don't.
https://wiki.php.net/rfc/ternary_associativity
>PHP RFC: Deprecate left-associative ternary operator
>Unlike most (all?) other languages, the ternary operator in PHP is left-associative rather than right-associative. The left-associative behavior is generally not useful and confusing for programmers who switch between different languages. This RFC proposes to deprecate and remove left-associativity for the ternary operator and require explicit use of parentheses instead.
>As an example, the code
return $a == 1 ? 'one'
: $a == 2 ? 'two'
: $a == 3 ? 'three'
: $a == 4 ? 'four'
: 'other';
>would in most (all?) other languages be interpreted as return $a == 1 ? 'one'
: ($a == 2 ? 'two'
: ($a == 3 ? 'three'
: ($a == 4 ? 'four'
: 'other')));
>which is both the useful and intuitive interpretation. In PHP, it is instead interpreted as return ((($a == 1 ? 'one'
: $a == 2) ? 'two'
: $a == 3) ? 'three'
: $a == 4) ? 'four'
: 'other';
>which is generally not what was intended.https://stackoverflow.com/questions/20559150/ternary-operato...
>Q: Can someone please explain what is happening here and why it is printing 'four'?
>A: Because your whole expression evaluates as if it was (......) ? 'four' : 'other'. Since the first element is probably something truthy, it gives you 'four'. In saner languages, where ?: has right associativity, the whole expression evaluates as if it was $a == 1 ? 'one' : (......), where if $a is not 1, you go on to test other things.
>PHP Sadness: Ternary operator associativity
>The ternary operator is left-associative and therefore behaves entirely incorrectly:
https://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/
>PHP: a fractal of bad design
>Unlike (literally!) every other language with a similar operator, ?: is left associative.