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

Andrew Koenig ark at research.att.com
Fri Feb 7 21:31:05 EST 2003


Ian> I use this pattern all the time:

Ian> if x:
Ian>     val = y
Ian> else:
Ian>     val = z

Ian> And I *hate* it.

I don't exactly hate it, but I don't like it either ...
and the reason I don't like it is that I have to write "val"
twice.  That's twice as many opportunities to get it wrong.

In effect, the problem is that the surrounding context has to
be duplicated on both sides of the if.  Which means that the
argument in favor of an if-then-else expression gets stronger
as the surrounding context grows.  Consider:

   val = map(lambda x: <something>, y)

Now imagine that the <something> contains a conditional, such as

   val = map(lambda x: str(x) if x >= 0 else "(" + str(-x) + ")", y)

It's pretty clear what this does: It generates a string representation
for the values in y, putting the negative values in parentheses rather
than putting a sign in front of them.

In order to change this to an if statement, you must either repeat
the context or introduce temporaries, such as

        def f(x):
            if x >= 0:
                return x
            else:
                return "(" + str(-x) + ")"
        val = map(f, y)

Examples such as this are why I say that if-then-else expressions are
particularly useful in conjunction with lambda expressions.

-- 
Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark




More information about the Python-list mailing list