Sunday, December 11, 2016

Simulating the C switch statement in Python

By Vasudev Ram


Switch example image attribution

While reviewing some code, I got the idea of simulating the switch statement of the C language, in Python. (Python does not have a built-in switch statement.)

Here is a short program that shows how to do it. It uses a dict and the two-argument version of its .get() method.
from __future__ import print_function

'''
simulate_c_switch.py
A program to demonstrate how to partially simulate 
the C switch statement in Python. The fall-through 
behavior of the C switch statement is not supported,
but the "default" case is.
Author: Vasudev Ram
Copyright 2016 Vasudev Ram
Web site: https://vasudevram.github.io
Blog: http://jugad2.blogspot.com
Product store: https://gumroad.com/vasudevram
Twitter: https://mobile.twitter.com/vasudevram
'''

def one_func():
    print('one_func called')

def two_func():
    print('two_func called')

def default_func():
    print('default_func called')

d = {1: one_func, 2: two_func}

for a in (1, 2, 3, None):
    print("a = {}: ".format(a), end="")
    d.get(a, default_func)()
And here is the output of running the program:
$ python simulate_c_switch.py
a = 1: one_func called
a = 2: two_func called
a = 3: default_func called
a = None: default_func called

Notice that 3 and None are not in the dict d (whose keys represent arguments to the "switch"), but when they are passed as arguments, a function (default_func) does gets called. This is the implementation of the default case.

There are a few differences from the actual C switch:

- the code to be executed for each case has to be a function here; in C it can be any one or more statements; but for this technique, in most cases, you should be able to put all the code you want executed for any case, into a custom function.

- the fall-through behavior of the C switch is not supported. But that, while it can be convenient, does lead to less readable code, and also is not structured programming, in the sense of having just one entry point and one exit point for any block of code. (Of course that is not very strictly followed these days, and even Python supports returning from multiple places in a function or method.)

After writing this program, it struck me that others may have thought of this too, so I did a search for this phrase:

does python have a switch statement

and here is one hit:

Replacements for switch statement in Python?

I guess we can find others by varying the phrase a bit.

Check out this related post, for another kind of dynamic function dispatch:

Driving Python function execution from a text file

- Enjoy.

- Vasudev Ram - Online Python training and consulting

Get updates on my software products / ebooks / courses.

Jump to posts: Python   DLang   xtopdf

Subscribe to my blog by email

My ActiveState recipes

FlyWheel - Managed WordPress Hosting



No comments: