Yet Another Switch-Case Syntax Proposal

L

Lucas Malor

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top