"?:", "a and b or c" or "iif"

Michael P. Reilly arcege at shore.net
Wed May 26 08:21:08 EDT 1999


Thomas Wouters <thomas at xs4all.nl> wrote:
: On Tue, May 25, 1999 at 04:35:19PM +0000, Fred L. Drake wrote:

:>   Assuming you're emulating "x ? a : b"....
:>   This isn't quite it.  Using C's ?:, only one of a or b is evaluated
:> when the expression is evaluated.  iif(x, a, b) evaluates both a and
:> b.  Sometimes this is acceptable, but not if either a or b has side
:> effects or is expensive to evaluate.

: [..]

:>   Perhaps Python 2 can fix this shortcoming; I'd often like to use
:> something equivalent to ?:.

: Wait, wait. What's wrong with using 

: x and a or b

: for constructs similar to '?:' ? It shortcuts like '?:', and you can nest it
: to create those hideously unreadable lines C programmers love so much :) (To
: be honest, i love them too, in C, when i dont care about readability. I even
: used to use them in MOO a lot -- i have two lines of 300+ characters with 7
: layers of '?|' (MOO's '?:') constructs, on some old MOO object.)

: Earlier someone said it wasn't equivalent -- but why not ? At least it's
: more equivalent than an iif() function, isn't it ? Excuse my ignorance if i
: missed something obvious.

The only problem with it is the semantics when "x" evaluates to true
and "a" evaluates to a false value.  In that case, "b" will be
evaluated (possibly with a side-effect).  The "?:" expression would not
evaluate "b" if "x" was true, regardless of the value of "a".

So if you can guarentee that your "a" would evaluate to some true
value, it works:
  msg = have_spam and "eggs" or "toast"
The string "eggs" is not empty, so it is always true.

  -Arcege





More information about the Python-list mailing list