Yet Another Switch-Case Syntax Proposal
Chris Angelico
rosuav at gmail.com
Sun Apr 6 14:07:02 EDT 2014
On Mon, Apr 7, 2014 at 3:49 AM, Marco S. <elbarbun at 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
More information about the Python-list
mailing list