[Python-Dev] Switch statement

Guido van Rossum guido at python.org
Thu Jun 22 17:20:48 CEST 2006

On 6/22/06, Roger Miller <rogermiller at alum.mit.edu> wrote:
> Part of the readability advantage of a switch over an if/elif chain is
> the semantic parallelism, which would make me question mixing different
> tests in the same switch.  What if the operator moved into the switch
> header?
>      switch x ==:
>          case 1: foo(x)
>         case 2, 3: bar(x)
>      switch x in:
>         case (1, 3, 5): do_odd(x)
>         case (2, 4, 6): do_even(x)
> "switch x:" could be equivalent to "switch x ==:", for the common case.

That's difficult (I mean impossible) for Python's parser, since x ==
is also the legal start of an expression.

> I've also been wondering whether the 'case' keyword is really necessary?
>   Would any ambiguities or other parsing problems arise if you wrote:
>      switch x:
>          1: foo(x)
>         2: bar(x)
> It is debatable whether this is more or less readable, but it seemed
> like an interesting question for the language lawyers.

That's no problem for the parser, as long as the expressions are
indented. ABC did this.

But I think I like an explicit case keyword better; it gives a better
error message if the indentation is forgotten.

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

More information about the Python-Dev mailing list