Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #70064

Re: Yet Another Switch-Case Syntax Proposal

Date 2014-04-10 21:15 +0000
Subject Re: Yet Another Switch-Case Syntax Proposal
From "Lucas Malor" <3kywjyds5d@snkmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.9150.1397164552.18130.python-list@python.org> (permalink)

Show all headers | View raw


On 6 April 2014 20:07, Chris Angelico rosuav-at-gmail.com |python-list@python.org| <d7v3ztas9t@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.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Yet Another Switch-Case Syntax Proposal "Lucas Malor" <3kywjyds5d@snkmail.com> - 2014-04-10 21:15 +0000

csiph-web