LWN.net Logo

It's not completely equivalent

It's not completely equivalent

Posted Mar 13, 2003 11:01 UTC (Thu) by rschroev (subscriber, #4164)
In reply to: No need of new syntax by sokol
Parent article: Choosing a ternary operator for Python

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.


(Log in to post comments)

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.

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