[Python-Dev] Switch statement

Josiah Carlson jcarlson at uci.edu
Sat Jun 24 02:21:47 CEST 2006

"Eric Sumner" <kd5bjo at gmail.com> wrote:
> On 6/23/06, Guido van Rossum <guido at python.org> wrote:
> > No; in order to make it possible to use a single dict lookup for
> > dispatch, the set members are expanded into the dict key. If you have
> > a large contiguous range, you'll be better off (sometimes *much*
> > better) doing an explicit if/elif check before entering the switch.
> In that case, I would argue that the proposed syntax is misleading.
> Regardless of how it is implemented, a switch statement is
> conceptually a chain of if/elif statements.  As such, the 'in'
> keyword, if it is allowed at all, should behave like it does in if
> statements, rather than it does in loops.  If, for implementation
> reasons, you want to ensure that all of the sets are enumerable, I
> would recommend a syntax like this:
>    "case" ["*"] expression ("," ["*"] expression)* ":" suite
> This is consistent with parameter lists, which emphasizes that the
> sequences are being enumerated instead of simply tested against.

You apparently missed the post where Guido expressed that he believes
that one of the valid motivators for the switch statement and the
dict-based dispatching was for that of speed improvements.  He also
already stated that cases could essentially only be examples for which
Python does pre-computation and the storing of constants (he didn't use
those words, and there are caveats with regards to module.attr and
global 'constants', but that was the gist I got from it).

As such, because any explicit range object is neither dict-accessable as
the values in the range would be, nor are they generally precomputed (or
precomputable) as constants (like (1,2,3) is and 1+1 should be), your
particular use-case (range objects that may implement __contains__ fast,
but whose __iter__ returns a huge number of values if it were
implemented as such) is not covered under switch/case, and we would
likely point you back off to if/elif/else.

This is a good thing, because if switch/case ends up functionally
identical to if/elif/else, then it has no purpose as a construct.  On
the other hand, because it is different from if/elif/else, and it is
different in such a way to make certain blocks of code (arguably) easier
to read or understand, (likely provably) faster, then it actually has a
purpose and use.

 - Josiah

More information about the Python-Dev mailing list