[Python-Dev] Re: switch statement

Michael Chermside mcherm at mcherm.com
Wed Apr 27 23:09:59 CEST 2005


Guido writes:
> You mean like this?
>
>     if x > 0:
>        ...normal case...
>     elif y > 0:
>         ....abnormal case...
>     else:
>         ...edge case...
>
> You have guts to call that bad style! :-)

Well, maybe, but this:

    if x == 1:
       do_number_1()
    elif x == 2:
       do_number_2()
    elif x == 3:
       do_number_3()
    elif y == 4:
       do_number_4()
    elif x == 5:
       do_number_5()
    else:
       raise ValueError

is clearly bad style. (Even knowing what I did here, how long does it
take you to find the problem? Hint: line 7.)

I've seen Jim's recipe in the cookbook, and as I said there, I'm impressed
by the clever implementation, but I think it's unwise. PEP 275 proposes
an O(1) solution... either by compiler optimization of certain
if-elif-else structures, or via a new syntax with 'switch' and 'case'
keywords. (I prefer the keywords version myself... that optimization
seems awefully messy, and wouldn't help with the problem above.) Jim's
recipe fixes the problem given above, but it's a O(n) solution, and to
me the words 'switch' and 'case' just *scream* "O(1)". But perhaps
it's worthwhile, just because it avoids repeating "x ==".

Really, this seems like a direct analog of another frequently-heard
Python gripe: the lack of a conditional expression. After all, the
problems with these two code snippets:

     if x == 1:        |    if condition_1:
        do_1()         |        y = 1
     elif x == 2:      |    elif condition_2:
        do_2()         |        y = 2
     elif x == 3:      |    elif condition_3:
        do_3()         |        y = 3
     else:             |    else:
        default()      |        y = 4

is the repetition of "x ==" and of "y =". As my earlier example
demonstrates, a structure like this in which the "x ==" or the
"y =" VARIES has a totally different *meaning* to the programmer
than one in which the "x ==" or "y =" is the same for every
single branch.

But let's not start discussing conditional expressions now,
because there's already more traffic on the list than I can read.

-- Michael Chermside



More information about the Python-Dev mailing list