If one were to add switch into Python, wouldn't it be desirable to make a pattern matching switch (think the "match" or "case" construct from Haskell or ML)? Python currently has poor support for union/sum types in general, not just enumerations. It feels weird to add better support for enumerations while ignoring the broader use case.
If a switch statement gets added to Python and I still need to examine ASTs by a long chain of if-elif and isinstance and so on I will cry. -- Devin On Wed, Apr 2, 2014 at 7:53 AM, Lucas Malor <3kywjyd...@snkmail.com> wrote: > Hi all. I would proposeto you all a switch-case syntax for Python. I already > read PEP 3103 and I'm not completely satisfied by any of the proposed > solutions. This is my proposal: > > switch_stmt ::= "switch" identifier "case" expression_list ":" suite > ("case" expression_list ":" suite)* > ["else" ":" suite] > > or, more simply: > > > > switch x case var1: > .... > case var2: > ... > case var3: > ... > else: > ... > > > > Expression list should yield an iterable. The case suite will be executed if > the variable of the identifier is a member of the iterable. > > For example, in a "switch x" statement, the code "case iterable: " is > identical to "if x in iterable: " (or elif etc). So if you want to perform > the same case block for more than one value, you have only to specify a > tuple, a range etc. > I would suggest to add an exception for non-iterable variables, so that you > don't have to write "case var, : " but simply "case var: " and it will be > identical to "if x == var: ". It's a bit tricky but the alternative is ugly. > > Fallthrough is disabled by default. The continue keyword cause to skip all > the remaining current case suite. The next case will be checked. You can't > use the continue keyword in the else clause. > > Some random remarks: > 1. switch is on the same line of the first case. This will avoid any > unpythonic syntaxes like: > switch x > case var1: > ... > > or > > switch x: > case var1: > ... > > 2. Fallthrough is disabled by default because IMHO it's what non-programmers > expect and that's what programmer usually needs more. I don't think a switch > with such a syntax needs a break statement. > > 3. As an alternative, the continue statement could be written only at the end > of a case suite; it will be less powerful and not consistent with the other > compound statements, but it will improve readability. > > 4. I decided to not use already existing keyword like "if" or "in", since it > will be misleading and problematic for syntax highlighters. > > > Tell me what you think about. > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list