PEP 308: an additional "select/case" survey option
Clark C. Evans
cce at clarkevans.com
Wed Mar 5 13:12:39 EST 2003
On Wed, Mar 05, 2003 at 03:57:50PM +0000, Stephen Horne wrote:
| If I want to write, for example...
|
| a = (if (b != 0) then a/b else 1000)
| + (if (d != 0) then c/d else 1000)
| + (if (h != 0) then g/h else 1000))
|
| ... then readability is best served by keeping each conditional on a
| single line so that vertical alignment can emphasize the pattern.
Ok.
a = ((when b != 0: a/b
else: 1000)
+ (when d != 0: c/d
else: 1000)
+ (when h != 0: g/h
else: 1000))
Which I admit isn't very pretty. However, if you assume that
in the select/when proposal a missing else clause causes
non-matches to evaluate to None, you get...
a = ( ((when b != 0: a/b) or 1000))
+ ((when d != 0: c/d) or 1000))
+ ((when h != 0: g/h) or 1000)))
I guess this is one extra level of parenthesis... but then
again the if/then proposal could be limited to such a scope
(not having an else).
| That said, I think that some form of 'select' could have merit - but
| as an alternative to, rather than a replacement for, a simpler
| conditional expression notation.
Hmm. As soon as you add "else" to the if clause, I think
it should be time to consider how to make it more flexible.
Best,
Clark
def sum(lst):
res = 0
for itm in lst:
res += itm
return res
def div(numerator, denominator, ifzero = None):
if denominator != 0: return numerator/denominator
return ifzero
a = sum([div(x,y) for x,y in ((a,b),(c,d),(g,h))])
More information about the Python-list
mailing list