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

Dan Schmidt dfan at dfan.org
Sat Feb 8 11:36:35 EST 2003


"Sean Ross" <sross at connectmail.carleton.ca> writes:

| Mostly, I just wanted to avoid a specific edge case someone mention much
| earlier in the thread:
| 
|     if x if C else y:
|         ...do stuff...
| 
| which just seemed ugly. But, then:
| 
|     if x when C else y:
|         ...do stuff...
| 
| is only marginally less ugly. And, of course
| 
|     if if C then x else y:
|         ...do stuff...
| 
| is worse than both. Oh, and then there's
| 
|     if C ? x : y:
|         ...do stuff...
| 
| or, as was proposed earlier:
| 
|     if C ? x else y:
|         ...do stuff...
| 
| None of the above constructs is particularly wonderful, none is
| particularly clear, and, hopefully, none of them would ever be
| used. But, of those listed, I find the 'when' variant to be the
| least confusing.

Actually, this is the one case (the expressions being boolean) where I
would use

   if (C and x) or y:
       ...do stuff...

even if there were a ternary operator, because that to me is the
actual logic behind the code.  (I do hate 'C and x or y' when x and y
are not boolean expressions, though.)

But if I were going to do it with a ternary operator, I'd just
parenthesize:

   if (x if C else y):
       ...do stuff...

People parenthesize for clarity all the time.  I don't see any reason
to assume that they wouldn't do it in this case too.

Dan

-- 
http://www.dfan.org




More information about the Python-list mailing list