[Tutor] Case ? (fwd)

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Jul 6 20:16:16 CEST 2005



---------- Forwarded message ----------
Date: Wed, 6 Jul 2005 00:01:52 -0700 (PDT)
From: Mike Cheponis <mac at Wireless.Com>
To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] Case ?

On Tue, 5 Jul 2005, Danny Yoo wrote:

> 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

Thanks, comments below.

Since this didn't come out in Python 2.4, is it "automatically" re-considered for 2.5 ?


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

Sure, this is nice.

It does require one to "functionalize" each case, tho, rather than "doing the work" in the body of the case.


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


Years ago, I did this:

#define is :{
#define esac break;}


So above becomes:

switch(state) {
    case STATE_1 is
 	 doStateOneStuff();
    esac

    case STATE_2 is
 	 doStateTwoStuff();
    esac

    case STATE_3 is
 	doStateThreeStuff();
    esac

    default is      doDefaultAction(); esac
}


I worked with one C programmer who said that's "not C" and refused to use this simple technique to reduce bugginess.  He was from Russia, and seemed pretty convinced about a lot of things ;-) but I don't work with him anymore.


> Hope this helps!

yes, greatly!  Thanks -Mike



More information about the Tutor mailing list