[Python-Dev] Switch statement

Eric Sumner kd5bjo at gmail.com
Sat Jun 24 04:08:10 CEST 2006


> > 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).

I admit that I came into this discussion in the middle, and my initial
post was for informational (to me) purposes only.  I did not mean to
imply by that post that the proposal was flawed in any way, just to
verify that I properly understood the proposal.  I am sorry if I was
unclear about this.

> 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.

I concur.  I actually suspected as much prior to my original message
on this topic, but I wanted to make sure I was understanding things
correctly before attempting to make a suggestion.

> 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.

Again, I concur.  My point was not that the mechanics of the construct
were incorrect, but that the proposed syntax misrepresented its
function.  Again, I am sorry if I was unclear about this.

  -- Eric Sumner


More information about the Python-Dev mailing list