PEP 308: an additional "select/case" survey option

Stephen Horne intentionally at blank.co.uk
Wed Mar 5 21:49:14 EST 2003


On Wed, 5 Mar 2003 18:12:39 +0000, "Clark C. Evans"
<cce at clarkevans.com> wrote:

>   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.

I wouldn't really complain that much about this example - my point is
mainly about the validity of the preference. After all, a conditional
doesn't need to get all that complex and you need multiple lines
anyway.

> 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).

The reason I dislike this has nothing to do with parentheses - it's
keeping a part of the old and/or paradigm, and in particular it keeps
the main 'bug' in the and/or paradigm - i.e.

  (when true : None) or 1000

evaluates to 1000 - not None.

It's an improvement in that it 'reads better' than the and/or paradigm
but, IMO, it's not enough of an improvement.

But getting back to the point, just because you've used the 'or'
operator to express the 'else' part does not change the fact that
you've put each conditional on a single line. You've spelled it
differently, but you've structured and formatted it exactly the same
way that I did ;-)

>    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))])

I'd personally keep your div, but replace the rest with...

  temp = ((a,b), (c,d), (g,h))
  reduce (operator.add, [div(x,y) for x,y in temp])

But not always. Creating lists of tuples purely to exploit list
comprehensions etc. can easily distract from the real intention of the
code. It could depend on how those variables are related, for
instance, or where they came from. And of course, I wouldn't
necessarily want to apply the same operator on the LHS of each line -
it could just easily have been...

  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)))

-- 
steve at ninereeds dot fsnet dot co dot uk




More information about the Python-list mailing list