Yet Another Switch-Case Syntax Proposal

Chris Angelico rosuav at gmail.com
Thu Apr 3 18:20:41 EDT 2014


On Fri, Apr 4, 2014 at 5:12 AM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> 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.

Still not an ideal demonstration of fall-through. Here's a much more
useful form:

switch get("version") case 0:
    commands_to_get_to_version_1
case 1:
    commands_to_get_to_version_2
case 2:
    commands_to_get_to_version_3

    # Version 3 is current.
    set("version", 3)
case 3:
    break
else:
    raise UnknownVersionError("Unexpected version!")

With fall-through, you don't need a loop around that. You jump to the
appropriate point and start executing code until you get to the bottom
(apart from the else, which obviously should never happen).

To implement this in current Python, I'd probably do all the
comparisons as inequalities:

v = get("version")
if v<0:
    raise UnknownVersionError("Version is below zero!")
if v<1:
    commands_to_get_to_version_1
if v<2:
    commands_to_get_to_version_2

    # Version 3 is current.
    set("version", 3)
if v>3:
    raise UnknownVersionError("Version is moving backward!")

Which means this isn't really a terribly compelling use-case; but I
think it's a better one than overlapping ranges. Fall-through in
C-like languages completely ignores the case labels on subsequent
sections, and executes them because of their position in the file; I'm
not sure how it's looking with the current proposals, but it seems the
case statements would have to be written to catch the values from
above.

ChrisA



More information about the Python-list mailing list