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


Groups > comp.lang.python > #69599

Re: Yet Another Switch-Case Syntax Proposal

References <8084-1396540962-768613@sneakemail.com>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2014-04-03 12:12 -0600
Subject Re: Yet Another Switch-Case Syntax Proposal
Newsgroups comp.lang.python
Message-ID <mailman.8848.1396548791.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Thu, Apr 3, 2014 at 10:02 AM, Lucas Malor <3kywjyds5d@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.

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


Thread

Re: Yet Another Switch-Case Syntax Proposal Ian Kelly <ian.g.kelly@gmail.com> - 2014-04-03 12:12 -0600

csiph-web