Yet Another Switch-Case Syntax Proposal

Marco S. elbarbun at gmail.com
Sun Apr 6 13:49:45 EDT 2014


On 3 April 2014 20:12, Ian Kelly ian.g.kelly-at-gmail.com |
python-list at python.org| <dnl5yyr7ut at sneakemail.com> wrote:
> Use this instead [of continue]:
>
> switch day case in ("Mon", "Tue", "Wed", "Thu", "Fri"):
>     go_to_work = True
>     day_type = "ferial"
>     if day in ("Tue", "Thu"):
>         lunch_time = datetime.time(11, 30)
>         meeting_time = datetime.time(12, 30)
>     else:
>         lunch_time = datetime.time(12)
>         meeting_time = datetime.time(14)
> case in ("Sat", "Sun"):
>     go_to_work = False
>     day_type = "festive"
>
> You get an extra level of indentation this way, but it reads less like
> spaghetti code.


Well, if you have to add an if-else to your switch-case, it means
switch-case syntax is not so useful.
An alternative is to imitate elif, so you'll have elcase. This way we don't
need continue. Since I do not like elcasein, the best solution is to do as
suggested by many of you, so case in instead of casein.
But if you can write case in, why you can't write "case" comp_operator in
general? With this syntax you can do also case is not, case > etc... Your
example will turn into

briefing_days = ("Tue", "Thu")
festive_days = ("Sat", "Sun")

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"


If you don't specify comp_operator, the default is ==. Example:

switch day_num case 1:
    day_str = "Monday"
elcase 2:
    day_str = "Thursday"
else:
    day_str = "etcetera"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20140406/8847fcb6/attachment.html>


More information about the Python-list mailing list