FW: Switch statements again

Bengt Richter bokr at oz.net
Fri Jan 17 04:56:39 CET 2003

On Thu, 16 Jan 2003 11:10:43 -0500, "John Roth" <johnroth at ameritech.net> wrote:

>"Bengt Richter" <bokr at oz.net> wrote in message
>news:b05r5n$oan$0 at
>> On Wed, 15 Jan 2003 18:21:40 -0500, Steven Scott
><bodoni26 at resnet.gatech.edu> wrote:
>> >Quoting Steven Scott <Steven.Scott at Synchrologic.com>:
>> >>=20
>> >> If/elif/else remains the most common method.  If Python ever gains
>> >> something
>> >> like a switch statement you can bet the farm it won't have a "fall
>> >"
>> >> feature though, so the way you've coded your C switch statement
>> >t
>> >> work.
>> >>=20
>> >
>> >but the absolute /only/ reason you'd use a switch over an if (besides
>> >looking better) is fall through.
>> >
>> Well, if you look at the code for an optimized C switch I think you'll
>> find another reason. I.e., if you can predetermine that all the switch
>> case _constants_ form a compact sequence of values, you can generate a
>> computed jump through a table that is a lot faster than a series of
>> conditional jumps, and even in cases where you have to introduce
>> jumps for boundary cases you may still gain.
>If all of the switch case _constants_ are single constants, you can use
>a dictionary or a list of functions.
The trouble with (current style) functions is that you can't put code in them
to rebind names in the caller's scope (i.e., the scope where you'd be in an
if/elif version of the case statement).

However, if you could define transparent same-scope functions, it could be different,
and also avoid most of the call overhead. I posted some musings along those lines
in a thread some time ago.

>And I'd agree that I don't want fall through. Ever. It creates difficult
>find bugs.
I agree also. Please add my -1 to the vote on fall-through.

Bengt Richter

More information about the Python-list mailing list