[Python-Dev] switch-based programming in Python

Skip Montanaro skip@pobox.com (Skip Montanaro)
Thu, 08 Nov 2001 17:23:09 +0100


    >> If you think you need an annotation, you may just as well propose to
    >> introduce a switch statement into the language.

    mal> True, but that would probably be even harder to get accepted on
    mal> python-dev (or would it ;-) ?
 
    >> switch x:
    >>   case 'foo':
    >>     ...
    >>   case 'bar':
    >>     ...
    >>   case 42:
    >>     ...

If you restrict the case values to hashable literals do you need "case"?
One new keyword would be easier than two for Guido to swallow...

One other post I saw in this thread used explicit breaks as is required in
C.  I would get rid of that.  When the current case's code ends, control
flow should just jump to the end of the switch.  No other block in Python
falls through like that does it?  Leaving out the break statement can also
be a subtle source of errors in C code and can probably be eliminated
without much loss of expressiveness.  Besides, switches (especially those
used to implement state machines) are often executed inside loops.  If break
is used to terminate the current case, it's not available to break out of
the enclosing loop and you're stuck with using a try/except/raise
combination or setting some state variable and checking it at the bottom of
each loop.

Skip