[Python-Dev] Adding C ternary select (a?b:c) to Python?

Christian Tismer tismer@tismer.com
Tue, 01 Feb 2000 18:22:15 +0100


Gordon McMillan wrote:
> 
> Fred L. Drake, Jr. writes:
> > Greg Stein writes:
> >  > p.s. I'm against a ternary operator. use an if/else statement. use
> >  > def instead of lambda (lambda is the only rational basis given so far to
> >  > add the operator, but it is bogus to start with)
> >
> >   Actually, the places I'd use it most would be probably be in
> > constructing parameters to string formatting operations.  Grepping
> > back in my memory, that's usually where I've wanted it.
> 
> Boy does that ring a big bell. Was ambivalent, now I'm all for it
> (either C syntax or "then" syntax, don't care).

So am I! Conditional expressions make very much sense for
constructing objects on-the-fly. It is quite common to
denote tuples, lists and dicts directly in Python code,
like so:

mapping_table = {
	1: "one",
	2: "two",
}

and so on. To parameterise them, we can either use different tables
embedded in an if, or use an expression inside the denotation:

language = 1

mapping_table = {
	1: ("one", "eins")[language],
	2: ("two", "zwei")[language],
}

but with expressions, we get to

mapping_table = {
	1: language == 0 ? "one" : "eins",
	2: language == 0 ? "two" : "zwei",
}

Well, maybe I had better chosen a different example, since the
language example looks better with indexing here.

How would we spell an elif? Would we at all?

# languages: 0 - English  1 - German  2 - Finnish

mapping_table = {
	1: language == 0 ? "one" : language == 1 ? "eins", "yksi",
	2: language == 0 ? "two" : language == 2 ? "zwei", "kaksi",
	3: language == 0 ? "three" : language == 2 ? "drei", "kolme",
}

(yes the zero slot is missing - forgot what that is in Finnish:)

Would conditionals also be valid on the LHS of assignments?

target ? a : b = language ? "one" : "eins"

grmbl - chris

-- 
Christian Tismer             :^)   <mailto:tismer@appliedbiometrics.com>
Applied Biometrics GmbH      :     Have a break! Take a ride on Python's
Düppelstr. 31                :    *Starship* http://starship.python.net
12163 Berlin                 :     PGP key -> http://wwwkeys.pgp.net
PGP Fingerprint       E182 71C7 1A9D 66E9 9D15  D3CC D4D7 93E2 1FAE F6DF
     we're tired of banana software - shipped green, ripens at home