Hacker News new | ask | show | jobs
by Asraelite 1798 days ago
Is this official, encouraged syntax? It looks like it's just exploiting short-circuit evaluation. `bar && foo || baz` works in Javascript as well for example.
3 comments

No.

In fact, nearly 20 years ago PEP 308 ("Conditional Expressions") was made so people wouldn't need to resort to this sort of syntax - https://www.python.org/dev/peps/pep-0308/ .

Quoting from the Python FAQ from 2.6 at https://web.archive.org/web/20151030070641if_/https://docs.p... :

> In many cases you can mimic a ? b : c with a and b or c, but there’s a flaw: if b is zero (or empty, or None – anything that tests false) then c will be selected instead. In many cases you can prove by looking at the code that this can’t happen (e.g. because b is a constant or has a type that can never be false), but in general this can be a problem.

> Tim Peters (who wishes it was Steve Majewski) suggested the following solution: (a and [b] or [c])[0].

I have seen it a lot of code over the years, sometimes referred to as "shorthand ternary" or the "and-or-trick". In Python and/or do not return a boolean, but one of its input arguments. So I am going to say it is official syntax, but I don't know to what extent it's encouraged
Not only in python, but in most scripting languages. It’s hard to find one that doesn’t. But it’s neither official, nor ternary syntax anywhere.

  true and false or true
  true ?   false :  true
These are not equivalent. If the second argument is evaluated as false, the “ternary” breaks.

Lua suggests to use this as ternary, but it has only two false values (nil, false), which reduces the number of problematic cases a little.

It saves a character in code golf, but as others have pointed out, it's unsafe.

    a if b else c #+1 byte
    a and b or c  #buggy
    (c,b)[not a]  #ok in general
    a and 1or c   #-1 byte if b is a constant
    (b,c)[a]      #-4 byte if a is boolean