[Python-Dev] Switch statement
skip at pobox.com
skip at pobox.com
Mon Jun 12 00:36:11 CEST 2006
talin> Since you don't have the 'fall-through' behavior of C, I would
talin> also assume that you could associate more than one value with a
talin> case, i.e.:
talin> case 'a', 'b', 'c':
talin> ...
As Andrew Koenig pointed out, that's not discussed in the PEP. Given the
various examples though, I would have to assume the above is equivalent to
case ('a', 'b', 'c'):
...
since in all cases the PEP implies a single expression.
talin> It seems to me that the value of a 'switch' statement is that it
talin> is a computed jump - that is, instead of having to iteratively
talin> test a bunch of alternatives, you can directly jump to the code
talin> for a specific value.
I agree, but that of course limits the expressions to constants which can be
evaluated at compile-time as I indicated in my previous mail. Also, as
someone else pointed out, that probably prevents something like
START_TOKEN = '<'
END_TOKEN = '>'
...
switch expr:
case START_TOKEN:
...
case END_TOKEN:
...
The PEP states that the case clauses must accept constants, but the sample
implementation allows arbitrary expressions. If we assume that the case
expressions need not be constants, does that force the compiler to evaluate
the case expressions in the order given in the file? To make my dumb
example from yesterday even dumber:
def f():
switch raw_input("enter b, d or f:"):
case incr('a'):
print 'yay! a b!'
case incr('b'):
print 'yay! a d!'
case incr('c'):
print 'yay! an f!'
else:
print 'hey dummy! I said b, d or f!'
_n = 0
def incr(c):
global _n
try:
return chr(ord(c)+1+_n)
finally:
_n += 1
print _n
The cases must be evaluated in the order they are written for the example to
work properly.
The tension between efficient run-time and Python's highly dynamic nature
would seem to prevent the creation of a switch statement that will satisfy
all demands.
Skip
More information about the Python-Dev
mailing list