[Python-Dev] Switch statement

Ka-Ping Yee python-dev at zesty.ca
Sat Jun 24 20:29:18 CEST 2006


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.

Consider:

    "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."

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?)


-- ?!ng


More information about the Python-Dev mailing list