A library approach to the ternary operator
Alex Martelli
aleax at aleax.it
Sat Mar 22 05:28:09 EST 2003
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[0]
> ---------------------
I would name this 'choose' (let's avoid the confusion with the select
module and function therein, please!) AND make it VERY picky to help
catch usage errors:
def choose(x):
assert type(x) is list
assert len(x) == 1
return x[0]
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".
> select(condition and [true_result] or [false_result])
>
> it's just enough prettier than
>
> (condition and [true_result] or [false_result])[0]
>
> 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, 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.
Alex
More information about the Python-list
mailing list