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

Andrew Koenig ark at research.att.com
Fri Feb 7 15:16:18 EST 2003


Jamie> Little annoyances like that add up, and make code harder to
Jamie> read.  I like the fact that Python keeps things simple and
Jamie> consistent, and I'm perfectly happy to trade the conciseness
Jamie> offered by this proposed syntax for the clarity of doing it
Jamie> "the long way",

Jamie>     if simple-test-expression:
Jamie>         big-long-complicated-expression
Jamie>     else:
Jamie>         ...

The trouble is that there are contexts, such as function arguments,
in which one would like to use this form but it's not allowed.

For example, suppose ints is a list of numbers, and we want to
create a list of strings each of which represents the value of
the corresponding number, except that if the number is negative,
we would like the string to be "?".

Some people would write something like this:

        strs = []
        for i in ints:
            if i < 0:
                strs.append("?")
            else:
                strs.append(str(i))

but others (including me) would like to be able to write this:

        strs = [("?" if i < 0 else str(i)) for i in ints]

I find this example easier to understand than the previous one.

I think that if you like list comprehensions and lambda expressions,
you'll probably like PEP 308; if you don't, you probably won't.


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




More information about the Python-list mailing list