[Python-Dev] Switch statement
Guido van Rossum
guido at python.org
Mon Jun 19 18:53:44 CEST 2006
On 6/19/06, Raymond Hettinger <rhettinger at ewtllc.com> wrote:
> Guido van Rossum wrote:
> On 6/18/06, Josiah Carlson <jcarlson at uci.edu> wrote:
>
> [...] Offering arbitrary expressions whose
> meaning can vary at runtime would kill any potential speedup (the
> ultimate purpose for having a switch statement), [...]
>
> Um, is this dogma? Wouldn't a switch statement also be a welcome
> addition to the readability? I haven't had the time to follow this
> thread (still catching up on my Google 50%) but I'm not sure I agree
> with the idea that a switch should only exist for speedup.
>
> A switch-statement offers only a modest readability improvement over
> if-elif chains.
Probably, which is why it hasn't been added yet. :-)
But there is a definite readability improvement in that you *know*
that it's always the same variable that is being compared and that no
other conditions are snuck into some branches.
> If a proposal introduces a switch-statement but doesn't
> support fast dispatch, then it loses much of its appeal. Historically, the
> switch-statement discussions centered around fast dispatch without function
> call overhead or loss of direct read/write to local variables (see
> sre_compile.py and sre_parse.py for code would would see a speed benefit but
> almost no improvement in readability).
Well yes duh, of course a switch syntax should be as fast as a
corresponding if/elif dispatch series. (I look upon
dict-of-functions-based dispatch as a tool for a completely different
use case.)
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.
--
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-Dev
mailing list