[Python-Dev] Switch statement

Josiah Carlson jcarlson at uci.edu
Tue Jun 20 07:26:36 CEST 2006

"Guido van Rossum" <guido at python.org> wrote:
> Perhaps I misunderstood Josiah's comment; I thought he was implying
> that a switch should be significantly *faster* than if/elif, and was
> arguing against features that would jeopardize that speedup. I would
> think that it would be fine if some switches could be compiled into
> some kind of lookup table while others would just be translated into a
> series of if/elifs. As long as the compiler can tell the difference.

I personally don't find switch/case statements to be significantly (if
at all) easier to read than if/elif/else chains, but that is subjective,
and I note that Ka-Ping finds switch/case to be significantly easier to

Regardless of readability (I know that readability counts), TOOWTDI. If
we allow somewhat arbitrary cases, then any potential speedup may be
thrown away (which would bother those of us who use dispatching), and we
essentially get a different syntax for if/elif/else.  I don't know about
everyone else, but I'm not looking for a different syntax for
if/elif/else, I'm looking for fast dispatch with some reasonable syntax.

In my opinion, the most reasonable syntax is a semantic change for fast
dispatch inside of specifically crafted if/elif chains of the form:
    if/elif non_dotted_name == constant_expression:
As stated various ways by various people, you can generate a hash table
during function definition (or otherwise), verify that the value of
non_dotted_name is hashable, and jump to particular offsets.  If you are
careful with your offsets, you can even have parallel if/elif/else tests
that fall through in the case of a 'non-hashable'.

There is a drawback to the non-syntax if/elif/else optimization,
specifically that someone could find that their dispatch mysteriously
got slower when they went from x==1 to including some other comparison
operator in the chain somewhere.  Well, that and the somewhat restricted
set of optimizations, but we seem to be headed into that restricted set
of optimizations anyways.

One benefit to the non-syntax optimization is that it seems like it could
be implemented as a bytecode hack, allowing us to punt on the entire
discussion, and really decide on whether such a decorator should be in
the standard library (assuming someone is willing to write the decorator).

 - Josiah

More information about the Python-Dev mailing list