Yet Another Switch-Case Syntax Proposal

Ian Kelly ian.g.kelly at gmail.com
Thu Apr 3 14:12:21 EDT 2014


On Thu, Apr 3, 2014 at 10:02 AM, Lucas Malor <3kywjyds5d at snkmail.com> wrote:
>> __contains__ is not part of the interface for iterables
>
> For what I know there's not an Iterable interface. For example List simply extends Object. I hope that an ABC Iterable class will be introduced in a future.

It already exists:

>>> import collections.abc
>>> isinstance([1,2,3], collections.abc.Iterable)
True

>> Instead of disabling fallthrough by default, why not disable it all together?
>
> I was tempted but there are cases in which it's useful. An example
>
> switch day casein ("Monday", "Thursday", "Wednesday", "Tuesday", "Friday"):
>     gotowork = True
>     continue
> casein ("Monday", "Thursday", "Wednesday", "Tuesday", "Friday"):
>     daytype = "ferial"
> casein ("Saturday", "Sunday")
>     daytype = "festive"

I don't see how it's useful there.  The first two cases are the same,
so just combine the code into one suite.  For overlapping cases where
the intersection needs to be handled by both suites, you can match
against the union and use conditionals to determine in more detail
which code to run.  For example, if you would write:

switch day case in ("Mon", "Wed", "Fri"):
    lunch_time = datetime.time(12)
    meeting_time = datetime.time(14)
    continue
case in ("Tue", "Thu"):
    lunch_time = datetime.time(11, 30)
    meeting_time = datetime.time(12, 30)
    continue
case in ("Mon", "Tue", "Wed", "Thu", "Fri"):
    go_to_work = True
    day_type = "ferial"
case in ("Sat", "Sun"):
    go_to_work = False
    day_type = "festive"

Use this instead:

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.



More information about the Python-list mailing list