[Python-Dev] Switch statement
Guido van Rossum
guido at python.org
Fri Jun 23 20:55:06 CEST 2006
On 6/23/06, Fredrik Lundh <fredrik at pythonware.com> wrote:
> Guido van Rossum wrote:
> > (3) A switch is implemented using a dict which is precomputed at the
> > same time its static expressions are precomputed. The switch
> > expression must be hashable. Overlap between different cases will
> > raise an exception at precomputation time.
> +0 on switch/case, but -0.5 on a "in terms of implementation" rather
> than "in terms of existing language constructs" approach.
> as I mentioned before, I'd prefer if the switch/case/case-in/else was
> defined in terms of a corresponding if/elif/else construct (but where
> the controlling expression is only evaluated once).
> after all, Python's a dynamic language, and I'm not convinced that I
> would never want to use dynamically evaluated case values. just map
> switch EXPR:
> case E1:
> case in E2:
> VAR = EXPR
> if VAR == E1:
> elif VAR in E2:
> where VAR is a temporary variable, and case and case-in clauses can be
> freely mixed, and leave the rest to the code generator. (we could even
> allow "switch EXPR [as VAR]" to match a certain other sugar construct).
This used to be my position. I switched after considering the
alternatives for what should happen if either the switch expression or
one or more of the case expressions is unhashable. (Not to mention if
one of them has a broken __hash__ method.) Unless all values are
literals (or at least compile-time constant expressions involving only
literals) the compiler can't know whether any particular switch could
involve non-hashable values, and it would have to write code that
catches exceptions from hashing and falls back to an if/elif chain
implementation (unless you don't care at all about speedups). I don't
think that static would help enough; static doesn't promise that the
value is hashable.
> I'm also a K&R guy, so switch/case/case-in/else should all have the same
> indent. anything else is just sloppy design.
I'm on the fence about the exact syntax. I see four alternatives: we
can use case or not, and we can indent it or not. The only weird thing
about not indenting the cases is that python-mode.el and all other
IDEs would have be taught that the line following switch ...: should
not be indented.
But all things considered I'm probably most in favor of unindented
cases using the case keyword; working at Google has taught me that
indentation levels are a precious resource, and I'm slightly
uncomfortable with not having an explicit case keyword in the light of
coding errors involving typos or misindents.
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-Dev