[Python-ideas] "else" expression ":"

David Mertz mertz at gnosis.cx
Sat Apr 13 21:01:03 CEST 2013


On Apr 13, 2013, at 11:24 AM, Peter Norvig wrote:
> Here's an idea to address this.  What do you think of the syntax
>      "else" expression ":"
> for example:
> if val > 0:
>     return +1
> elif val < 0:
>     return -1
> else val == 0:
>     return 0

I often write code like:

  if cond1:
      doThing1()
  elif cond2:
      doThing2()
  # ... more steps here ...
  return something

I guess implicitly I think of this as a less verbose form of:

  if cond1:
      doThing1()
  elif cond2:
      doThing2()
  else:
      pass  # No need to do anything if not cond1 and not cond2

That is, the situation where every block of the condition ends in a return statement is a special case, and by no means universal to the use of if/elif/else.  In particular, not every time I use if/elif do I want a "catch the remaining cases" block, since it is often only in some enumerated special circumstances I want any processing to occur in the compound block.

I think the "else with boolean" is definitely readable, modulo exactly what exception is raised if it is violated.  However, it feels like the explicit 'assert' statement in those cases where we expect exhaustive conditions is already available.  Moreover, we can always add a final else to document our belief that conditions are exhaustive:

  if val > 0:
      return +1
  elif val < 0:
      return -1
  elif val == 0:
      return 0
  else:
      raise ValueError("'val' is not negative, positive, or zero! Check the properties of arithmetic")


--
mertz@     THIS MESSAGE WAS BROUGHT TO YOU BY:       v i
gnosis             Postmodern Enterprises            s r
.cx        MAKERS OF CHAOS....                       i u
           LOOK FOR IT IN A NEIGHBORHOOD NEAR YOU    g s






More information about the Python-ideas mailing list