[Python-Dev] Switch statement

Nick Coghlan ncoghlan at gmail.com
Mon Jun 19 16:10:09 CEST 2006

Phillip J. Eby wrote:
>>> Either way would work, and both would allow multiple versions of the same
>>> switch statement to be spun off as closures without losing their 
>> "constant"
>>> nature or expressiveness.  It's just a question of which one is easier to
>>> explain.  Python already has both types of one-time initialization:
>>> function defaults are computed at definition time, and modules are only
>>> loaded once, the first time you import them.
>> I would go with the former rather than the latter, if only for
>> flexibility.
> There's no difference in flexibility.  In either case, the dictionary 
> should be kept in a cell in the function's closure, not with the code 
> object.  It would simply be a difference in *when* the values were 
> computed, and by which code object.  To be done at function definition 
> time, the enclosing code block would have to do it, which would be sort of 
> weird from a compiler perspective, and there would be an additional problem 
> with getting the line number tables correct.  But that's going to be tricky 
> no matter which way it's done.

Caching on first use would be the easiest to explain I think. Something like:

     if jump_dict is NULL:
         jump_dict = {FIRST_CASE  : JUMP_TARGET_1,
                      SECOND_CASE : JUMP_TARGET_2,
                      THIRD_CASE  : JUMP_TARGET_3}
     jump_to_case(value, jump_dict)

'jump_dict' would be held in a cell on the function's closure (since the 
calculated case values might depend on global or closure variables)
'jump_to_case' would be the new opcode, taking two arguments off the stack 
(the jump dictionary and the switch value), executing the matching case (if 
any) and jumping to the end of the switch statement.
If no case is matched, then fall through to the else clause and then jump to 
the end of the statement.

Then the optimisation of the case where all of the case expressions are 
literals would come under the purview of a constant-folding compiler 
automatically when it figures out that the dictionary literal only contains 


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-Dev mailing list