Is there no switch function in Python

Roy Smith roy at panix.com
Fri Sep 10 09:35:27 EDT 2004


In article <1Zb*VOguq at news.chiark.greenend.org.uk>,
 Sion Arrowsmith <siona at chiark.greenend.org.uk> wrote:

> In article <CR20d.46131$Vf.2380522 at news000.worldonline.dk>,
> Rudi Hansen <rsh_remove_this_ at pobox.dk> wrote:
> >I dont seem to be able to find the switch statement in Python.
> >
> >I would like to be able to do
> >
> >switch(var)
> >    case 1 :
> >        print "var = 1"
> >    case 2:
> >        print "var = 2"
> 
> 5 lines, 55 characters including the print statements.

It's even longer if you include the required "break" statement at the 
end of case 1 (assuming you're talking about a C-style switch statement 
with fall-through cases).

That being said, there are times when I miss switch.  For some kinds of 
multi-branch logic, I think it expresses the meaning better than a 
string of if's.  But it's hardly necessary.

The real reason, IMHO, switch existed in C was because it would let the 
compiler build very efficient jump tables for switches with many cases.  
Imagine switching on the ascii value of a character and having a 128 
different cases.  The compiler could build a 128 entry jump table and 
the switch statement would compile down to a single machine instruction.



More information about the Python-list mailing list