[Python-Dev] Switch statement

Talin talin at acm.org
Mon Jun 12 01:18:59 CEST 2006


skip at pobox.com wrote:
>     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'):
>         ...

I had recognized that ambiguity as well, but chose not to mention it :)

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

Here's another ugly thought experiment, not meant as a serious proposal; 
it's intent is to stimulate ideas by breaking preconceptions. Suppose we 
take the notion of a computed jump literally:

    def myfunc( x ):
       goto dispatcher[ x ]

       section s1:
          ...

       section s2:
          ...

    dispatcher=dict('a'=myfunc.s1, 'b'=myfunc.s2)

No, I am *not* proposing that Python add a goto statement. What I am 
really talking about is the idea that you could (somehow) use a 
dictionary as the input to a control construct.

In the above example, rather than allowing arbitrary constant 
expressions as cases, we would require the compiler to generate a set of 
opaque tokens representing various code fragments. These fragments would 
be exactly like inner functions, except that they don't have their own 
scope (and therefore have no parameters either).

Since the jump labels are symbols generated by the compiler, there's no 
ambiguity about when they get evaluated.

The above example also allows these labels to be accessed externally 
from the function by defining attributes on the function object itself 
which correspond to the code fragments.

So in the example, the dictionary which associates specific values with 
executable sections is created once, at runtime, but before the first 
time that myfunc is called.

Of course, this is quite a bit clumsier than a switch statement, which 
is why I say its not a serious proposal.

-- Talin


More information about the Python-Dev mailing list