(test?return_true:return_false)

Erik Max Francis max at alcyone.com
Fri Jan 24 19:39:47 EST 2003


Sean Ross wrote:

> Or, from the "Python Cookbook":
>     (matches == 1 and [''] or ['es'])[0]
> or
>     ('', 'es')[matches != 1]
> or, for plurals in particular,
>     's'*(matches != 1)

Yes, you can use lambdas as well.  Both of these solutions are
self-defeating:  The purpose for using the conditional operator is so
that the meaning is clear.  With each incrementally correct solution,
the code becomes more and more obfuscated to the point of defeating the
entire purpose for introducing it.

The goal isn't compacting as much code is one line.  The goal is doing
it cleanly, in a way that's obvious.

I've wished for a conditional operator in Python since I first started
using it.  I've used (a, b)[p] (where p is known to be 0 or 1) notaton
since it's fairly readable.  I won't use the p and a or b because of the
potential mishap.  I certainly won't use the "proper," although
obfuscated solutions involving singleton lists or lambdas; that would
negate the entire purpose I want it for.

There are always ways to do it; the question is whether those ways
belong in production code (especially in such an inherently readable and
transparent language such as Python) or in obfuscated programming
contests.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ I grow with each breath that I take / I cherish my freedom
\__/ Chante Moore
    ZOE / http://www.alcyone.com/pyos/zoe/
 A simple Python OpenGL rendering engine.




More information about the Python-list mailing list