A library approach to the ternary operator
dave at boost-consulting.com
Sun Mar 23 02:56:03 CET 2003
Alex Martelli <aleax at aleax.it> writes:
> David Abrahams wrote:
>> I still like the idea of a ternary operator, and I'm not afraid to
>> admit it. However, none of the language solutions were particularly
>> compelling, so I got to thinking about a library approach and came up
>> with this one:
>> ---- ternary.py-------
>> def select(x): return x
> I would name this 'choose' (let's avoid the confusion with the select
> module and function therein, please!)
No problem; I don't know all the standard libs as well as you do or
I'd have avoided 'select' in the first place.
> AND make it VERY picky to help
> catch usage errors:
> def choose(x):
> assert type(x) is list
> assert len(x) == 1
> return x
Oh sure: I would do that in real code but I was seduced by the
> Note that with -O the assert statements get compiled away, so there
> is no real price to pay for this pickiness when the code gets into
> production use -- it's just there to help catch (likely!) mis-usage
> during the development phase.
> But, yes, I do like the overall approach.
>> # then...
>> from ternary import *
> (Note what WILL happen each time this from statement is executed
> in a module that also does "import select" -- that's why it's
> somewhat important to pick a better name for the function...!).
> Another likely name might be "pick".
y = choose(x < 0 and [22.5] or [f(x)])
y = ternary(x < 0 and [22.5] or [f(x)])
y = pick(x < 0 and [22.5] or [f(x)])
y = cond(x < 0 and [22.5] or [f(x)])
y = if_(x < 0 and [22.5] or [f(x)])
I guess I like the last two, and the last one best of all, because
in my mind there's a nice association between the function name and
the adjacent condition.
>> select(condition and [true_result] or [false_result])
>> it's just enough prettier than
>> (condition and [true_result] or [false_result])
>> to be worth using. Having a function name ("select") there gives us
>> something to attach a nice verbose comment to, while the above, since
>> it uses only language primitives, remains obscure.
> Yes, I concur. Moreover, this ternary.py can easily be widely
> spread and popularized
or spurned, as the case may be ;-)
> to establish a usage base for 'choose' IF people like the approach
> (I'm not gonna guess if they will) -- this may help make a case for
> 'choose' as a built-in, later, if and only if people like and use it
> so much as to warrant that.
It's always nicer to have a transition plan that goes through a
library-only approach first without making core language changes.
That gives the concept a chance to live or die on its own without
forcing people to accept more than they can stomach.
More information about the Python-list