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

Alex Martelli aleax at aleax.it
Fri Feb 7 22:40:52 CET 2003


Andrew Koenig wrote:
   ...
> 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.

Me too, but offhand it appears to me that the downsides of
the forms you can use today for this kind of need, such as:

         strs = [ i < 0 and '?' or str(i) for i in ints]

or

         strs = [ (str(i), '?')[i<0] for i in ints]

may not be that extreme, with respect to the proposed new form,
as to warrant the new construct.  So, I'm of two minds about this.
There ARE better use cases -- where both expressions can have
side effects and can possibly be false -- but not many.  Readability
is so-so either way.  I dunno...


> 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.

That may explain it -- I love LC's and detest Python's too-limited,
hobbled lambdas, so _of course_ I'm of two minds...;-).


Alex





More information about the Python-list mailing list