case/switch statement?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sat Jun 11 20:35:42 EDT 2005


On Sat, 11 Jun 2005 16:15:42 +0000, Joe Stevenson wrote:

> Hi all,
> 
> I skimmed through the docs for Python, and I did not find anything like 
> a case or switch statement.  I assume there is one and that I just 
> missed it.  Can someone please point me to the appropriate document, or 
> post an example?  I don't relish the idea especially long if-else 
> statements.

I don't relish the idea of especially long case statements.

I've never understood why something like:

if x = 5:
    do_this
elif x = 6:
    do_that
else:
    do_something_else

is supposed to be "bad", but

case of:
    x = 5:
        do_this
    x = 6:
        do_that
otherwise:
        do_something_else

is supposed to be "good".

(Choose whatever syntax you prefer for case statements, the principle
remains.)

Arguably, a case statement *might* allow the compiler to optimize the
code, maybe, sometimes. But in general, no such optimization is possible,
so a case statement is merely equivalent to a series of if...elif...
statements.

There is no case statement in Python. If you don't care about
readability, one alternative is to use a dictionary:

case = {5: do_this, 6: do_that}
case.get(x, do_something_else)()



-- 
Steven.




More information about the Python-list mailing list