[Python-Dev] Switch statement

Raymond Hettinger rhettinger at ewtllc.com
Mon Jun 19 22:24:02 CEST 2006

>> My thought is that we *should* define switching in terms of hash
>> tables.  It builds off of existing knowledge and therefore has a near
>> zero learning curve.  The implementation is straight-forward and there
>> are none of the hidden surprises that we would have with
>> fastpath/slowpath approaches which use different underlying magic
>> methods and do not guarantee order of execution.
> I'm not so sure about there being no hidden surprises. I betcha that
> there are quire a few bits of code that curerntly use the if/elif
> style and seem to beg for a switch statement that depend on the
> ordering of the tests. A typical example would be to have one of the
> earlier tests express an exception to a later test that is a range
> test. 

That's a tricky issue.  Whenever the cases overlap, I would expect a 
successive comparison approach to jump to the first match while a hash 
table approach would jump to the last match (just like a dictionary 
retains only the latest (key,value) pair when fed successive pairs with 
identical keys and differing values).

> (Surely we're going to support range tests... sre_compile.py
> uses 'in' almost as often as 'is'.)

When the ranges have a short length as they do in sre, I expect that the 
syntax would allow the range to be captured on one line but have 
multiple entries in the hash table which each dispatch to the same 
target code suite:

    switch x:
    case 0, 2, 4, 6:  handle_even()
    case 1, 3, 5, 9:  handle_odd()
    default:  handle_fractions()

Unfortunately, that approach is less than ideal for bigger ranges:

   switch x:
   case xrange(0,sys.maxint,2): handle_odd()
   case xrange(1,sys.maxint,2): handle_even()
   default: handle_fractions()

Other types of range checks get us back into the area of arbitrary 
expressions in case values and having to repeat the variable name:

   switch x:
   case x < 60:  return "too cold"
   case 60 <= x < 80:  return "just right"
   case 80 <= x: return "too hot"

Choose your poison.  How much range flexibility do you want and how much 
implementation and behavioral complexity are you willing to pay for it.

>> If use cases eventually emerge for an alternative path using successive
>> == comparisons, then it can always be considered and added later.  For
>> now, YAGNI (neither the functionality, nor the implementation headaches,
>> nor the complexity of explaining what it does under all the various 
>> cases).
> I say, let someone give a complete implementation a try, and then try
> to modify as much standard library code as possible to use it. Then
> report back. That would be a very interesting experiment to do. (And
> thanks for the pointer to sre_compile.py as a use case!)

Hmm, it could be time for the Georg bot to graduate to big game.
Georg, are you up to it?


More information about the Python-Dev mailing list