[Tutor] Case ?

Liam Clarke cyresse at gmail.com
Wed Jul 6 06:43:11 CEST 2005


Ah, the cascading broken case statement of doom.

On 7/6/05, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> 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
> 
> 
> 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!
> 
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



-- 
'There is only one basic human right, and that is to do as you damn well 
please.
And with it comes the only basic human duty, to take the consequences.'
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050706/10b552c7/attachment.htm


More information about the Tutor mailing list