[Python-Dev] Switch statement
Josiah Carlson
jcarlson at uci.edu
Tue Jun 13 01:07:18 CEST 2006
skip at pobox.com wrote:
>
>
> Greg> Before accepting this, we could do with some debate about the
> Greg> syntax. It's not a priori clear that C-style switch/case is the
> Greg> best thing to adopt.
>
> Oh sure. That debate should probably leverage PEP 275.
Along the lines of PEP 275, one of my concerns with the use of a
switch/case automatic conversion or even explicit syntax is that of
low-hanging fruit...
In my experience, switch/case statements are generally used to either
structure code explicitly with state handling code, improve performance
of such state handling, or both. I think that if we are going to be
modifying Python to include such a syntax or automatic conversion, those
standard use-cases be considered primary.
With that said, the low-hanging fruit, in my opinion, are precisely
those cases specified in PEP 275 in the Solution 1 option. For the
majority of use-cases that I've seen, automatic conversion for the
if/elif/else blocks with a hash table would cover this low-hanging fruit,
and would be a nice transparent optimization.
One other nice thing about such an optimization is that it could work
fine for known-immutable types (strings, ints, ...), and with work,
could preserve previous behavior for not-known-immutable types.*
- Josiah
* This would basically work by compiling the if/elif/else block normally,
adding a type check for the switched-on item, on success, switch to just
after the comparison operator in the if/elif/else bodies, and on failure,
proceed to the first comparison.
To handle the case of if x.i ==...: ... elif x.i == ...: ..., we could
state that the optimization will only occur if the 'switched on' value
is a bare name (x is OK, x.i and x[i] are not).
More information about the Python-Dev
mailing list