Alternative suggestion for conditional expressions (see PEP 308)

Jeff Shannon jeff at ccvcorp.com
Thu Jul 15 15:17:08 EDT 2004


Larry Bates wrote:

>Seems that every one of the examples can be done
>with a dictionary.
>  
>

While that may be true of the examples given here, it's not true of all 
cases.  The one possible real advantage of a conditional expression, as 
I see it, is shortcutting.  In cases where the conditionally-executed 
code has side effects, it can be important to ensure that *only* one 
branch is evaluated; creating an actual dictionary (whether permanent or 
temporary) will execute *all* branches.  For example, using neblackcat's 
proposed syntax (even though I'm *not* fond of it):

nextline = ?(FileOne.readline(), FileTwo.readline())[whichfile]

In this case, since reading a line from a file advances the filepointer, 
executing both will result in a line being "lost" from the non-selected 
file.  (I realize that in this specific example, one could use the 
conditional to select a file object and call readline() on the result of 
the conditional; I could also construct examples in which entirely 
different operations-with-side-effects are performed on each branch so 
that refactoring in that way isn't practical, or one branch is a string 
literal and the other has some side-effect, or whatever.)

Note that, while I do think it's important to be aware of this 
distinction, I'm not advocating the proposed syntax (I'm rather leery of 
using punctuation like that, as Peter Hansen mentions) or even 
necessarily advocating for a conditional expression at all.  I remain 
unconvinced of the need for an expression to do what can already be done 
with statements -- a conditional expression may be more concise, but 
conciseness more often hampers readability than helps it, and 
readability is very important.  I've heard the arguments that using a 
multiline if/else construct in order to set up parameters for a function 
call is ugly, but I personally find that to be no worse than the 
ugliness of conditional expressions...

Jeff Shannon
Technician/Programmer
Credit International






More information about the Python-list mailing list