[Python-Dev] Switch statement

skip at pobox.com skip at pobox.com
Sun Jun 11 00:53:14 CEST 2006

    Thomas> As the subject of this e-mail says, the attached patch adds a
    Thomas> "switch" statement to the Python language.

Thanks for the contribution.  I patched my sandbox and it built just fine.
I'm going out of town for a couple weeks, so I'll point out what everyone
else is thinking then duck out of the way:

    * Aside from the modified Grammar file there is no documentation.
    * There are no test cases.
    * Can you submit a patch on SourceForge?

Other than that, my trivial first attempt worked fine:

    #!/usr/bin/env python

    switch raw_input("enter a, b or c: "):
        case 'a':
            print 'yay! an a!'
        case 'b':
            print 'yay! a b!'
        case 'c':
            print 'yay! a c!'
            print 'hey dummy! I said a, b or c!'

(Need to teach python-mode about the switch and case keywords.)

You mentioned:

    Thomas> I got a bit lost as to why the SWITCH opcode is necessary for
    Thomas> the implementation of the PEP. The reasoning seems to be
    Thomas> improving performance, but I'm not sure how a new opcode could
    Thomas> improve performance.

Your implementation is straightforward, but uses a series of DUP_TOP and
COMPARE_OP instructions to compare each alternative expression to the
initial expression.  In many other languages the expression associated with
the case would be restricted to be a constant expression so that at compile
time a jump table or dictionary lookup could be used to jump straight to the
desired case.


More information about the Python-Dev mailing list