[Python-Dev] Switch statement
jcarlson at uci.edu
Sat Jun 24 21:57:19 CEST 2006
Ka-Ping Yee <python-dev at zesty.ca> wrote:
> On Fri, 23 Jun 2006, Josiah Carlson wrote:
> > This is a good thing, because if switch/case ends up functionally
> > identical to if/elif/else, then it has no purpose as a construct.
> This doesn't make sense as a rule.
> "If x.y ends up functionally identical to getattr(x, 'y'),
> then it has no purpose as a construct."
> "If print x ends up functionally identical to import sys;
> sys.stdout.write(str(x) + '\n'), then it has no purpose as
> a construct."
I agree with you completely, it doesn't make sense as a rule, but that
was not its intent. Note that I chose specific values of X and Y in "if
X is functionally identical to Y, then it has no purpose as a construct"
such that it did make sense.
> What matters is not whether it's *functionally* identical. What
> matters is whether it makes more sense to the reader and has a
> meaning that is likely to be what the writer wanted.
> "Evaluate the switch expression just once" is a semantic win.
> "Evaluate the switch expression just once, but throw an exception
> if the result is not hashable" is a weaker semantic win. (How
> often is that what the writer is thinking about?)
> "Throw an exception at compile time if the cases overlap" is also
> a weaker semantic win. (How often is this an actual mistake that
> the writer wants to be caught at compile time?)
> "Use the case values computed at compile time, not at runtime" doesn't
> seem like much of a win. (How often will this be what the writer
> intended, as opposed to a surprise hiding in the bushes?)
The reasons by themselves don't seem to make sense, until you look at
them in the scope from which the decisions were made. Just like
the word "Excelsior" makes no sense until you hear "Minnesota".
Those final three rules, when seen in the context of the rest of the
conversation, and with the understanding that one of the motivating
purposes is to improve execution time, do offer methods and mechanisms
to answer those motivations.
More information about the Python-Dev