[Python-Dev] switch-based programming in Python

Skip Montanaro skip@pobox.com (Skip Montanaro)
Thu, 8 Nov 2001 13:01:44 +0100


    mal> As mentioned in the posting: the compiler probably has to be given
    mal> some extra information to enable this sort of optimization. I'm not
    mal> sure how the information could be "encoded", though. Suggestions
    mal> are appreciated, as always :-)

I don't think you need anything extra if the RHS of the == is a hashable
literal of some sort and the LHS is always the same simple variable or
subscript expression.  If the compiler can recognize the structure (that may
be a big "if"), all you need is a dictionary of offsets stored in the
function's constants.  You just execute the equivalent of

    offset = jumptable.get(x, E)
    jumpby offset
    label 'one':
        ...
        jumpto endofswitch
    label two':
        ...
        jumpto endofswitch
    ...
    else:
        ...
        jumpto endofswitch

"E" is the offset of the else clause.  If none exists, E == the offset of
endofswitch.

It's possible that you can just analyze the parse tree before generating the
code.  If it matches the desired pattern you transform it to a switch-like
structure.  Of course, this presumes you use a parse tree as input to code
generation, unlike the current C-based compiler (but like the Python-based
compiler does?)

Skip