ternary operator

Alexander Schmolck a.schmolck at gmx.net
Tue Feb 4 19:09:41 EST 2003


gausebec-spam at paypal.com (David Gausebeck) writes:

> I've recently started using python from a primarily C/C++ background,
> and one of the annoyances that I ran into right away was the lack of a
> ternary ?: operator.

That python tries to seperate statements (assignment, conditionals etc.) and
expressions has it pros and cons. The pros are:

- it makes code more uniform (there is only one way to write an "if test"
  etc.)
- it makes cramming too many things into a single line painful. I have often
  found that python getting into my way of being too "clever" has helped me to
  write cleaner and better code.

I think you should maybe first "do as the Romans do" for a couple of kloc and
see how you like it then, before attempting to work around the "missing"
ternary (BTW: I don't think there is a language designed by people who knew
what they were doing that has a ternary operator; all the non-braindead
languages I've seen that allow conditionals in expressions don't distinguish
between expressions and statements to begin with).

> The C expression "a ? b : c" can be emulated in python with
> "a and b or c"
> if b is not false.  If b could be false, then you can use
> "(a and [b] or [c])[0]".
> 2) Is there any better workaround than the ones I've listed above?

Since you don't seem to want shortcircuting,``(b,c)[not a]`` maybe?


> Finally, a thought on the solution I'd like to see...  I agree that
> the C syntax of a ? b : c wouldn't really work nicely in python, but
> perhaps a unary ? operator acting on a list/tuple would.  Instead of
> "a ? b : c", python could support
> "?(a, b, c)".

<blech>

> 
> The main disadvantage I can see to the syntax at this point is that it
> wouldn't support short-circuiting.

Indeed the "disadvantage" of having a `if-else`-statement simply evaluate
everything seems to outweight the disturbingly ugly and cryptic syntax and the
waste of one of the few still unused non-alphanumeric characters for no
expressive gain.

alex




More information about the Python-list mailing list