LWN.net Logo

No need of new syntax

No need of new syntax

Posted Mar 13, 2003 10:42 UTC (Thu) by sokol (guest, #4383)
Parent article: Choosing a ternary operator for Python

I am not a Python user but it seems that even in its actual form, Python allows a very similar (and elegant IMHO) syntax:

<cond> and <expr1> or <expr2>
(you may put it in paranthesis if you like)

which works *exactly* in the same manner its C sibling:
<cond> ? <expr1> : <expr2>

So why all this hype ?


(Log in to post comments)

It's not completely equivalent

Posted Mar 13, 2003 11:01 UTC (Thu) by rschroev (subscriber, #4164) [Link]

As pointed out in the Python FAQ (http://www.python.org/cgi-bin/faqw.py?query=ternary&querytype=simple&casefold=yes&req=search), there is a problem:

"Is there an equivalent of C's "?:" ternary operator?
Not directly. 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."

There is a workaround though:

"Tim Peters (who wishes it was Steve Majewski) suggested the following solution: (a and [b] or [c])[0]. Because [b] is a singleton list it is never false, so the wrong path is never taken; then applying [0] to the whole thing gets the b or c that you really wanted. Ugly, but it gets you there in the rare cases where it is really inconvenient to rewrite your code using 'if'."

In any case, I think using 'and' and 'or' lowers the readability, because it is not obvious what the intent is. A real ternary operator is a good idea.

Re: It's not completely equivalent

Posted Mar 13, 2003 13:32 UTC (Thu) by sokol (guest, #4383) [Link]

Right. I appologize for suggesting a wrong solution.

No need of new syntax

Posted Mar 13, 2003 18:11 UTC (Thu) by petebull (guest, #7857) [Link]

And the operator is allowed as an lvalue as in:

(a ? b : c) = 5

Copyright © 2012, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds