[Python-Dev] Switch statement

Fredrik Lundh fredrik at pythonware.com
Sat Jun 24 19:04:50 CEST 2006

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), and then 
add an opcode that checks uses a separate dispatch object to check if 
fast dispatch is possible, and place that before an ordinary if/elif 

the dispatch object is created when the function object is created, 
along with default values and statics.  if fast dispatch cannot be used 
for a function instance, the dispatch object is set to None, and the 
dispatch opcode turns into a NOP.

(each switch statement should of course have it's own dispatch object).


More information about the Python-Dev mailing list