Equivalent to (a ? b : c) ?

Hrvoje Niksic hniksic at iskon.hr
Mon Dec 20 12:37:04 EST 1999


"maxm" <maxm at normik.dk> writes:

> ######################################################################
> ## Why aren't there any unary type expression like "(Test)?trueVal:falseVal"
> in Python?
> 
> Thanks to Python's dynamic typing you can easily add the C "?:"
> expression to the language by defining a single function that will
> work with all types:

No, this is not even close to C's ?: operator.  The trick you are
missing is that ?: is lazy.  For example:

x = foo() ? bar() : baz();

...will call foo(), and based on that will call either bar() or baz(),
never both.  Your ifexp() will evaluate both expressions.

The solution that is correct in all cases has been posted by others:

	((a and (b,)) or (c,))[0]



More information about the Python-list mailing list