<br>Ah, the cascading broken case statement of doom.<br>
<br><div><span class="gmail_quote">On 7/6/05, <b class="gmail_sendername">Danny Yoo</b> &lt;<a href="mailto:dyoo@hkn.eecs.berkeley.edu">dyoo@hkn.eecs.berkeley.edu</a>&gt; wrote:</span><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
<br><br>On Tue, 5 Jul 2005, Mike Cheponis wrote:<br><br>&gt; Why does Python not have a &quot;case&quot; statement, like C?<br><br><br>Hi Mike,<br><br>It's a proposed enhancement:<br><br>&nbsp;&nbsp;&nbsp;&nbsp;<a href="http://www.python.org/peps/pep-0275.html">
http://www.python.org/peps/pep-0275.html</a><br><br><br>That being said, a dispatch-table approach, using a dictionary, works well<br>in Python because it's not hard to use functions as values --- most people<br>haven't really missed case/switch statements in Python because dispatch
<br>tables can be very effective.<br><br><br>For example, something like this:<br><br>### C ###<br>switch(state) {<br>&nbsp;&nbsp;&nbsp;&nbsp;case STATE_1: doStateOneStuff();<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break;<br>&nbsp;&nbsp;&nbsp;&nbsp;case STATE_2: doStateTwoStuff();
<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break;<br>&nbsp;&nbsp;&nbsp;&nbsp;case STATE_3: doStateThreeStuff();<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break;<br>&nbsp;&nbsp;&nbsp;&nbsp;default:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;doDefaultAction();<br>######<br><br><br>has a natural translation into Python as:<br><br>### Python ###
<br>dispatchTable = { STATE_1: doStateOneStuff,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;STATE_2:
doStateTwoStuff,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;STATE_3:
doStateThreeStuff }<br>command = dispatchTable.get(state, doDefaultAction)<br>command()<br>######<br><br>where we're essentially mimicking the jump table that a case/switch<br>statement produces underneath the surface.<br>
<br><br>One other consideration about C's case/switch statement is its<br>bug-proneness: it's all too easy to programmers to accidently forget to<br>put 'break' in appropriate places in there.<br><br><br>Hope this helps!<br>
<br>_______________________________________________<br>Tutor maillist&nbsp;&nbsp;-&nbsp;&nbsp;<a href="mailto:Tutor@python.org">Tutor@python.org</a><br><a href="http://mail.python.org/mailman/listinfo/tutor">http://mail.python.org/mailman/listinfo/tutor
</a><br></blockquote></div><br><br><br>-- <br>'There is only one basic human right, and that is to do as you damn well please.<br>And with it comes the only basic human duty, to take the consequences.'