Yet Another Switch-Case Syntax Proposal

Lucas Malor 3kywjyds5d at snkmail.com
Thu Apr 10 17:15:44 EDT 2014


On 6 April 2014 20:07, Chris Angelico rosuav-at-gmail.com |python-list at python.org| <d7v3ztas9t at sneakemail.com> wrote:
> Here's a simpler form of the proposal, which might cover what you
> need. It's basically a short-hand if/elif tree.
>
> case expression comp_op expression:
>     suite
> case [comp_op] expression:
>     suite
> ....
> else:
>     suite

I like this solution, but I tought about a simpler one. Basically it's my first proposal with two modifications:
1. case / elcase instead of continue, as before
2. if the case expression is a *tuple* (and not any one iterable), case suite is executed if the switched expression is an element of the tuple.

If you want to match exactly a tuple, you have simply to put it into another tuple of length 1. Tricky but too much rare to care about.
To recap:

switch_stmt ::=  "switch" expression "case" expression_list ":" suite
    ("case" | "elcase" expression_list ":" suite)*
    ["else" ":" suite]
1. if expression_list is a tuple, the case suite will be executed if the switch expression is a member of the tuple.
2. if expression_list is not a tuple, the case suite will be executed if the switch expression is equal
Example:

briefing_days = ("Tue", "Thu")
normal_days = ("Mon", "Wed", "Fri")

switch day normal_days + briefing_days:
    go_to_work = True
    day_type = "weekday"
case normal_days:

    lunch_time = datetime.time(12)
    meeting_time = datetime.time(14)
elcase briefing_days:

    lunch_time = datetime.time(11, 30)
    meeting_time = datetime.time(12, 30)
else:

    go_to_work = False
    day_type = "festive"
    lunch_time = None
    meeting_time =None

Another example:
switch tarot case 0:
    card = "Fool"
case 1:
    card = "Alan Moore"
case 2:
    card = "High Priestess"
etc.



More information about the Python-list mailing list