[Python-Dev] Switch statement

Thomas Lee tom at vector-seven.com
Sun Jun 11 03:04:10 CEST 2006

On Sat, Jun 10, 2006 at 05:53:14PM -0500, skip at pobox.com wrote:
>     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?

You're right, of course. I'll sort the documentation and test cases out
as soon as I get a chance.
> 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.

I see. But restricting the switch to constants in the name of
performance may not make sense in a language like Python. Maybe this is
something for the PEP to discuss, but it seems such an implementation
would be confusing and sometimes it may not be possible to use a switch
case in place of if/elif/else statements at all.

Consider the following:



some_value = 'a'

switch some_value:
		print 'got a'
		print 'got b'
		print ':('


Although, conceptually, FAUX_CONST_A and FAUX_CONST_B are constants, a
'constants only' implementation would likely give a syntax error (see
expr_constant in Python/compile.c).
IMHO, this will lead to one of two things:

a) unnecessarily duplication of constant values for the purpose of using
them as case values
b) reverting back to if/elif/else

I do get the distinction, I'm just wondering if the usefulness of the semantics
(or lack thereof) are going to negate any potential performance
enhancements: if a switch statement is never used because it's only
useful in a narrow set of circumstances, then maybe we're looking to
improve performance in the wrong place?

Just thinking about it, maybe there could be two different code paths
for switch statements: one when all the case values are constants (the
'fast' one) and one where one or more are expressions. This would mean a
slightly longer compile time for switch statements while ensuring that
runtime execution is the maximum possible without placing any major
restrictions on what can be used as a case value.


Tom Lee

More information about the Python-Dev mailing list