substitute for c/java's ?:

Alex Martelli aleaxit at yahoo.com
Wed Jun 13 17:30:29 EDT 2001


"Jochen Riekhof" <jochen at riekhof.de> wrote in message
news:9g82qt$8ab$06$1 at news.t-online.com...
> Hi...
>
> > Instead I usually write:
> > if option: result = value1
> > else: result = value2
> > just dropping the newlines. It's more verbose than
> > result = option ? value1 : value2
> > but at least it's clean.
>
> Found a somewhat unclean solution that also has the drawback to process
both
> operands any way, but it is sometimes nice because short:
> result (value1, value2)[not option]
>
> It assumes that the only booleans emerging from not x are 1 and 0, I hope
> this is defind in the language.

Yes, it is.  But, as you noticed, it has drawbacks.

http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52310 has a
survey of possibilities.  Lloyd Goldwasser just added another neat one in
a comment:
    (a and b, not a and c)[not a]
this also relies on not a being 0 or 1 (which IS language-defined) and
doesn't evaluate the (b or c) operand it doesn't need, just as the
    ((a and [b]) or [c])[0]

Lloyd's idiom evaluates a three times (that's the downside) and is
minutely longer than the classic one, but it has an interesting
symmetry about it.  Since interest in such pursuits is better kept
at an aesthetic level, rather than being applied to production code,
I think Lloyd's solution may in fact be deemed neater...:-).


Alex








More information about the Python-list mailing list