[Python-Dev] Switch statement

Thomas Lee tom at vector-seven.com
Tue Jun 13 02:49:27 CEST 2006


On Mon, Jun 12, 2006 at 11:33:49PM +0200, Michael Walter wrote:
> Maybe "switch" became a keyword with the patch..
> 
> Regards,
> Michael
> 

That's correct.

> On 6/12/06, M.-A. Lemburg <mal at egenix.com> wrote:
> >
> > Could you upload your patch to SourceForge ? Then I could add
> > it to the PEP.
> >

It's already up there :) I thought I sent that through in another
e-mail, but maybe not:

http://sourceforge.net/tracker/index.php?func=detail&aid=1504199&group_id=5470&atid=305470

Complete with documentation changes and a unit test.

> > Thomas wrote a patch which implemented the switch statement
> > using an opcode. The reason was probably that switch works
> > a lot like e.g. the for-loop which also opens a new block.
> >

No, Skip explained this in an earlier e-mail: apparently some
programming languages use a compile-time generated lookup table
for switch statements rather than COMPARE_OP for each case. The
restriction is, of course, that you're stuck with constants for each
case statement.

In a programming language like Python, where there are no named
constants, the usefulness of such a construct might be questioned.
Again, see Skip's earlier e-mails.

> > Could you explain how your patch works ?
> >

1. Evaluate the "switch" expression so that it's at the top of the stack
2. For each case clause:
2.1. Generate a DUP_TOP to duplicate the switch value for a comparison
2.2. Evaluate the "case" expression
2.3. COMPARE_OP(PyCmp_EQ)
2.4. Jump to the next case statement if false
2.5. Otherwise, POP_TOP and execute the suite for the case clause
2.6. Then jump to 3
3. POP_TOP to remove the evaluated switch expression from the stack

As you can see from the above, my patch generates a COMPARE_OP for each
case, so you can use expressions - not just constants - for cases.

All of this is in the code found in Python/compile.c.

Cheers,
Tom

-- 
Tom Lee
http://www.vector-seven.com


----- End forwarded message -----

-- 
Tom Lee
http://www.vector-seven.com



More information about the Python-Dev mailing list