case/switch statement?
Dan Sommers
me at privacy.net
Sun Jun 12 08:33:32 EDT 2005
On Sun, 12 Jun 2005 10:35:42 +1000,
Steven D'Aprano <steve at REMOVETHIScyber.com.au> wrote:
> I don't relish the idea of especially long case statements.
> I've never understood why something like:
> if x = 5:
> do_this
> elif x = 6:
> do_that
> else:
> do_something_else
> is supposed to be "bad", but
> case of:
> x = 5:
> do_this
> x = 6:
> do_that
> otherwise:
> do_something_else
> is supposed to be "good".
In the truly general case, I agree.
But twist your second example slightly into this:
case x of:
5: do_this
6: do_that
otherwise: do_something_else
and the goodness is obvious: we're choosing functionality based on the
value of x, so it's nice to see x in only one place.
> Arguably, a case statement *might* allow the compiler to optimize the
> code, maybe, sometimes. But in general, no such optimization is
> possible, so a case statement is merely equivalent to a series of
> if...elif... statements.
I agree that in general, optimizing a series of if/elif statements is
tricky, but your first example is very command and exactly the kind of
code that a good optimizer *can* optimize (as long as "x" isn't
pathological in the sense that evaluating it also changes its value or
has other side effects).
> There is no case statement in Python. If you don't care about
> readability, one alternative is to use a dictionary:
> case = {5: do_this, 6: do_that}
> case.get(x, do_something_else)()
I find this very readable. YMMV.
I also find this easier to extend in the "case" (pardon the pun) that my
program expands and x might now be 7 or 8 (or "foo" or 3j).
The biggest drawback here, as others have noted in previous discussions,
is that the do_* functions execute in a separate scope.
Regards,
Dan
--
Dan Sommers
<http://www.tombstonezero.net/dan/>
More information about the Python-list
mailing list