[Python-Dev] Switch statement

Ron Adam rrr at ronadam.com
Sat Jun 24 22:08:21 CEST 2006


Fredrik Lundh wrote:
> Guido van Rossum wrote:
> 
>  >> just map
>>>      switch EXPR:
>>>      case E1:
>>>          ...
>>>      case in E2:
>>>          ...
>>>      else:
>>>          ...
>>>
>>> to
>>>
>>>      VAR = EXPR
>>>      if VAR == E1:
>>>          ...
>>>      elif VAR in E2:
>>>          ...
>>>      else:
>>>          ...
>>>
>>> where VAR is a temporary variable, and case and case-in clauses can be
>>> freely mixed, and leave the rest to the code generator.  (we could even
>>> allow "switch EXPR [as VAR]" to match a certain other sugar construct).

>> This used to be my position. I switched after considering the
>> alternatives for what should happen if either the switch expression or
>> one or more of the case expressions is unhashable.

> I don't see this as much of a problem, really: we can simply restrict 
> the optimization to well-known data types ("homogenous" switches using 
> integers or strings should cover 99.9% of all practical cases)

+1  This would keep it simple to use.


A possibility that hasn't been mentioned yet is to supply a precomputed 
jump table to a switch explicitly.

     table = {expr1:1, expr2:2, ... }

     for value in data:
         switch table[value]:
        	    case 1: ...
             case 2: ...
             ...
             else: ...

(I prefer indented case's, but it's not the point here.  I can get use 
them it not being indented.)

It is an easy matter to lift evaluation of the switch table expressions 
out of inner loops or even out of functions. (if it's needed of course)


Or an alternate form may allow a pre-evaluated jump table to be 
explicitly substituted directly at the time of use. (would this be 
possible?)

     def switcher(value, table):
        switch value, table:
           case 1: ...
           case 2: ...
           ...
           else: ...


Cheers,
    Ron















More information about the Python-Dev mailing list