[Tutor] Case ?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Jul 5 19:38:44 CEST 2005



On Tue, 5 Jul 2005, Mike Cheponis wrote:

> Why does Python not have a "case" statement, like C?


Hi Mike,

It's a proposed enhancement:

    http://www.python.org/peps/pep-0275.html


That being said, a dispatch-table approach, using a dictionary, works well
in Python because it's not hard to use functions as values --- most people
haven't really missed case/switch statements in Python because dispatch
tables can be very effective.


For example, something like this:

### C ###
switch(state) {
    case STATE_1: doStateOneStuff();
                  break;
    case STATE_2: doStateTwoStuff();
                  break;
    case STATE_3: doStateThreeStuff();
                  break;
    default:      doDefaultAction();
######


has a natural translation into Python as:

### Python ###
dispatchTable = { STATE_1: doStateOneStuff,
                  STATE_2: doStateTwoStuff,
                  STATE_3: doStateThreeStuff }
command = dispatchTable.get(state, doDefaultAction)
command()
######

where we're essentially mimicking the jump table that a case/switch
statement produces underneath the surface.


One other consideration about C's case/switch statement is its
bug-proneness: it's all too easy to programmers to accidently forget to
put 'break' in appropriate places in there.


Hope this helps!



More information about the Tutor mailing list