something like "if" that returns a value?

Erik Max Francis max at alcyone.com
Mon Nov 11 12:56:18 EST 2002


Paul Rudin wrote:

> Yes, there are circumstances where this looks ok; but I'm a bit uneasy
> with this idiom. The main problems being:
> 
> - (as you say) you need to depend on the value of y;
> 
> - potentially both y and z are evaluated; and
> 
> - there's a degree of obfuscation here, the code is less
>   comprehensible than something like: if x then y else z.

Basically, you want the equivalent of the conditional (ternary) operator
in C, but in Python.  There is no such creature.  So you need to
compromise readability for a hack.  To get around the y being
potentially false problem, you need to do something even uglier:

	(x and [y] or [z])[0]

This will now work properly since a non-empty list is always true, but
most people will agree that this sacrifices readability to the breaking
point.

The conditional operator (in whatever Pythonic form) is one of the only
features I really miss from other languages, since if you're doing
trivial selection, it can actually increase readability.  But not if you
have to use some hacked-up expression that _almost_ acts like a
conditional operator, but not quite, meaning that you 1. have to
recognize the somewhat peculiar idiom and 2. more importantly, recognize
when the idiom won't work and avoid using it then.

Because of this, I use the simply (x, y)[p] selection when x and y are
constants and p is known to be Boolean, and simply avoid trying to use
conditional operators elsewhere in a language that (for better or worse)
does not have them.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ There is _never_ no hope left.  Remember.
\__/ Louis Wu
    Max Pandaemonium / http://www.maxpandaemonium.com/
 A sampling of Max Pandameonium's music.



More information about the Python-list mailing list