Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #69777
| References | <8084-1396540962-768613@sneakemail.com> <CALwzidmw0QbUbNw5PvwmHh+4ghguUhpEnY8TbBZYYyjZkpLBsw@mail.gmail.com> <CABbU2U8fcwZYBuDA6JNOdWgwkNaTWiPvCnR1Be4wCvF0vecU1g@mail.gmail.com> |
|---|---|
| Date | 2014-04-07 04:07 +1000 |
| Subject | Re: Yet Another Switch-Case Syntax Proposal |
| From | Chris Angelico <rosuav@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.8959.1396807975.18130.python-list@python.org> (permalink) |
On Mon, Apr 7, 2014 at 3:49 AM, Marco S. <elbarbun@gmail.com> wrote:
> switch day case in briefing_days:
>
> lunch_time = datetime.time(11, 30)
> meeting_time = datetime.time(12, 30)
> case not in briefing_days + festive_days:
>
> lunch_time = datetime.time(12)
> meeting_time = datetime.time(14)
> case in festive_days:
>
> go_to_work = False
> day_type = "festive"
> else:
>
> go_to_work = True
> day_type = "ferial"
>
> The if-else equivalent will be:
>
> if day in briefing_days:
>
> lunch_time = datetime.time(11, 30)
> meeting_time = datetime.time(12, 30)
> if day not in briefing_days + festive_days:
>
> lunch_time = datetime.time(12)
> meeting_time = datetime.time(14)
> if day in festive_days:
>
> go_to_work = False
> day_type = "festive"
> else:
>
> go_to_work = True
> day_type = "ferial"
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
This has a slight oddity of parsing (in that an expression can
normally have a comparison in it); if you really want to use the
result of a comparison inside a case block, you'd have to parenthesize
it. But it's easy enough to explain to a human.
case day in briefing_days:
lunch_time = datetime.time(11, 30)
meeting_time = datetime.time(12, 30)
case not in briefing_days + festive_days:
lunch_time = datetime.time(12)
meeting_time = datetime.time(14)
case in festive_days:
go_to_work = False
day_type = "festive"
else:
go_to_work = True
day_type = "ferial"
A case statement that opens with a comparison operator takes the value
from the previous case (without re-evaluating it); a case statement
that lacks a comparison altogether assumes == and does the above. In
either case (pardon the pun), the check will be done only if the
preceding case was false. An 'else' clause is effectively equivalent
to a 'case' that's always true.
Adds only one keyword to the language ("switch" is gone), and adds an
edge case to parsing that's unlikely to come up in non-contrived code.
ChrisA
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Yet Another Switch-Case Syntax Proposal Chris Angelico <rosuav@gmail.com> - 2014-04-07 04:07 +1000
csiph-web