For review: PEP 308 - If-then-else expression

jerf at compy.attbi.com jerf at compy.attbi.com
Tue Feb 11 03:34:47 CET 2003


On Mon, 10 Feb 2003 21:15:38 +0000, Parzival Herzog wrote:
>     (lambda: true_expression, lambda: false_expression)[not
> test_expression]()

I keep coming back to this. You can simplify a bit more with

def iif(condition, true, false):
	return (true, false)[not condition]()

and use it as

1. print iif(myFlyUnzipped, lambda: "aiee!", lambda: "phew!")
2. print if myFlyUnzipped: "aiee!" else: "phew!"
3. print iif(myFlyUnzipped, l: "aiee!", l: "phew!")

#1 does. It's not even that much more typing then some proposals still in
play, as #2 is.

My thinking is that while I'm fairly firmly against the special-case idea
of a ternary operator, I might accept something more generally useful that
happens to be able to spell ?: more accurately then _ and _ or _. However,
I keep coming back to the fact that we've already got it: Lambdas can be
used to defer execution, right there inline in the code.

While it's not impossible that some other equivalently generally useful
thing might come up (and I'm more likely to at least -0 the two I've seen,
integer -> [false, true] and some kind of C() condition function, with the
-0 representing the fact they both have problems, which, if fixed, would
turn them into +1), I haven't got any thoughts that aren't fully redundent
to what we already have in the form of lambda. 

If it's the typing that bothers you, float a PEP to make l: an alias for
lambda:. Or better yet, use an editor that lets you bind several
keystrokes to one keypress and tie "lambda:" to a key.

Creating a ternary operator seems like a step back to me (one more thing
to learn, and while it may seem simple in isolation all language features
interact multiplicatively!), while not giving any new power or
expressiveness that doesn't already exist; this whole debate strikes me as
an incredibly long discussion on how to shorten #1, which is an awfully
steep price to pay just to save a few keystrokes. As has been demonstrated
in practice, there's an awful lot of cases where _ and _ or _ is always OK
because the second parameter is always guarenteed true. While I'm not
willing to go out on a limb and claim this is representative, because
obvious cases where it wasn't sufficient don't show up (much... somebody
did have an example somewhere in the standard library for pluralizing
something in a unit test) and aren't counted, it *does* show the need for
a full-fledged ?: is not that acute.




More information about the Python-list mailing list