Wednesday, April 23, 2008

python: switch emulation

You know that python doesn't have switch statement. Guido says he doesn't want overload language python with statements to make it as much expressive as possible. But you can emulate 'switch' not only with 'if ... elif ... else' but with dictionary. Look:

{
    'one': lambda: 1,
    'two': lambda: 2
}.get('one', lambda: 0)()
You can create reusable 'switch' by creating dictionary that maps to callable objects and use it to call them by key. Also such 'switch' is mutable. This can be useful in some circumstances.

2 comments:

Paddy3118 said...

I use the technique here
with dictionary keyword2handler used as a jump table in line 181

- Paddy.

Ni@m said...

Yup, that's a well-known technique.
I believe that this technique will be more efficient than 'switch' in c/c++ if you are using plain array and strict range of values(like enum). I'm going to discover this.