[Python-Dev] switch-based programming in Python

Martin v. Loewis martin@v.loewis.de
Thu, 8 Nov 2001 16:43:32 +0100


> > this could be
> > established only by implementing it (you don't need to implement
> > the parser/compiler aspects, just the changes to ceval.c).
> 
> Hmm. How is that supposed to work ? I would like the compiler
> to generate different code for these "switch" statements. It
> would also have to generate the hash table and store it in
> the constants.

You would need to generate the byte code literally. Come up with a
byte code definition for this feature, support it in ceval, then come
up with a byte string that is an example for a large optimized "if"
chain, and generate a code object from it. Adapting Lib/compiler may
be helpful in generating byte code more flexible.

Only when it is known that this byte code that you generated more or
less manually indeed performs significantly faster, only then it would
be worthwhile looking into parser/compiler support for that byte code.

> Well, just try to write an XML parser using mxTextTools and the
> taggin engine which then generates a tag list to be processed in
> Python by an if..elif...else "switch" statement and
> compare the speed to a method call based one. You'll note the
> difference in performance (and have a second application ;-).

If it is unacceptably inefficient, perhaps this approach to XML
parsers is doomed to fail...

> This is just one aspect, though. I think that a lot more state
> machine like code could be written in Python if well-performing
> "switches" would be possible in Python. 

I think people have successfully used dictionaries of functions for
that. Why do you insist on generating long "if" chains?

> Now how could the compiler be provided with the needed
> information... ?

I still think this is the last question to ask. First define the
opcodes, and show us that they really do speed up things, then look
into the syntax needed to support this optimization.

If you think you need an annotation, you may just as well propose to
introduce a switch statement into the language.

  switch x:
    case 'foo':
      ...
    case 'bar':
      ...
    case 42:
      ...

Regards,
Martin