[Python-Dev] Switch statement
talin at acm.org
Sun Jun 11 23:15:13 CEST 2006
Greg Ewing wrote:
> skip at pobox.com wrote:
>> switch raw_input("enter a, b or c: "):
>> case 'a':
>> print 'yay! an a!'
>> case 'b':
>> print 'yay! a b!'
>> case 'c':
>> print 'yay! a c!'
>> print 'hey dummy! I said a, b or c!'
> Before accepting this, we could do with some debate about the
> syntax. It's not a priori clear that C-style switch/case is
> the best thing to adopt.
Since you don't have the 'fall-through' behavior of C, I would also
assume that you could associate more than one value with a case, i.e.:
case 'a', 'b', 'c':
It seems to me that the value of a 'switch' statement is that it is a
computed jump - that is, instead of having to iteratively test a bunch
of alternatives, you can directly jump to the code for a specific value.
I can see this being very useful for parser generators and state machine
code. At the moment, similar things can be done with hash tables of
functions, but those have a number of limitations, such as the fact that
they can't access local variables.
I don't have any specific syntax proposals, but I notice that the suite
that follows the switch statement is not a normal suite, but a
restricted one, and I am wondering if we could come up with a syntax
that avoids having a special suite.
Here's an (ugly) example, not meant as a serious proposal:
select (x) when 'a':
when 'b', 'c':
The only real difference between this and an if-else chain is that the
compiler knows that all of the test expressions are constants and can be
hashed at compile time.
More information about the Python-Dev