case/switch statement?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sun Jun 12 11:26:47 EDT 2005


On Sun, 12 Jun 2005 08:33:32 -0400, Dan Sommers wrote:

>> 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".
> 
> In the truly general case, I agree.
> 
> But twist your second example slightly into this:
> 
>     case x of:
>         5: do_this
>         6: do_that
>         otherwise: do_something_else
> 
> and the goodness is obvious:  we're choosing functionality based on the
> value of x, so it's nice to see x in only one place.

Yes. But now change the references to do_this and do_that to ten lines
of in-line code each, and add another dozen similar tests for 7, 8, etc,
and by the time you get to the third page you've forgotten what the
variable being tested is.

Now, you or I will obviously never write such hard-to-maintain code
<wink>, but some people will, and we'll have to maintain it.

It isn't at all obvious that case statements are more readable than
if...elif, nor are they necessarily faster at runtime, although they can
be. Against that occasional optimization and sometimes increase in
readability, you have disadvantages: more keywords, implicit tests instead
of explicit, new syntax to learn.



>> 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.
> 
> I agree that in general, optimizing a series of if/elif statements is
> tricky, but your first example is very command and exactly the kind of
> code that a good optimizer *can* optimize (as long as "x" isn't
> pathological in the sense that evaluating it also changes its value or
> has other side effects).

Yes. But that's also the sort of optimization that could be done for
if...elif as well, without introducing new syntax and new reserved words.

Case statements seem to be one of those things that Python newbies from
other languages automatically ask for, but the case for introducing case
(pun intended) doesn't appear to be strong enough to justify the amount of
verbiage spent on it.

And on that note, I will say no more on the subject.


-- 
Steven.




More information about the Python-list mailing list