[Python-Dev] Switch statement

Guido van Rossum guido at python.org
Thu Jun 22 22:00:15 CEST 2006


On 6/22/06, Ka-Ping Yee <python-dev at zesty.ca> wrote:
> On Wed, 21 Jun 2006, Guido van Rossum wrote:
> > (Note how I've switched to the switch-for-efficiency camp, since it
> > seems better to have clear semantics and a clear reason for the syntax
> > to be different from if/elif chains.)
>
> I don't think switch-for-efficiency (at least if efficiency is the
> primary design motivator) makes sense without some strong evidence
> that the use of if/elif constructs often causes a severe speed problem
> in many Python programs.  (Premature optimization and all that.)
> Long if/elif chains probably don't occur often enough or slow down
> programs enough to invent syntax *just* for speed; and even if they
> did, i don't think there's any precedent for a Python statement
> invented primarily as a speed optimization.

My position is more nuanced that that. I like having a switch because
it can make certain types of code more readable. (I keep referring to
sre_parse.py and sre_compile.py -- has anyone else looked at these at
all?) But I also like switch because it can be implemented using a
single dict lookup with a pre-computed dict, if certain conditions on
the cases are met. I find that those conditions generally met by code
that lends itself for using a switch. I believe that switch would be
better understood if it *always* precomputed the dict, and failed
immediately with an exception (at run time) if the precompilation
wasn't feasible.

> I'm hoping we can talk more about the question: How can a new statement
> help programmers express their intent more clearly?
>
> So far i've seen two possible answers to that question:
>
>     1.  The switched-on expression is written and evaluated just once.
>
>     2.  The cases could help you unpack things into local variables.
>
> (There was some discussion about unpacking earlier:
> http://mail.python.org/pipermail/python-dev/2005-April/052780.html
> which petered out, though there may still be the possibility of
> designing something quite useful and readable.)

I'm not convinced that the matching idea (which your URL seems to
refer to) works well enough in Python to consider. Anyway, it's a
completely different approach and should probably be discussed
separately rather than as a variant of switch/case.

-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-Dev mailing list