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


Groups > comp.lang.python > #69615 > unrolled thread

Re: Yet Another Switch-Case Syntax Proposal

Started byChris Angelico <rosuav@gmail.com>
First post2014-04-04 09:20 +1100
Last post2014-04-04 09:20 +1100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Yet Another Switch-Case Syntax Proposal Chris Angelico <rosuav@gmail.com> - 2014-04-04 09:20 +1100

#69615 — Re: Yet Another Switch-Case Syntax Proposal

FromChris Angelico <rosuav@gmail.com>
Date2014-04-04 09:20 +1100
SubjectRe: Yet Another Switch-Case Syntax Proposal
Message-ID<mailman.8860.1396563963.18130.python-list@python.org>
On Fri, Apr 4, 2014 at 5:12 AM, Ian Kelly <ian.g.kelly@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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web