Welcome, guest | Sign In | My Account | Store | Cart

This recipe shows a Python construct that can behave somewhat like C's switch statement. It is not a perfect one-to-one simulation. But it does have some of the features of the C switch. One feature not supported is the fall-through feature in C's switch.

Python, 30 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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)()

The recipe tries to provide something functionally equivalent to the C switch statement - not an exact replica of it in Python. One missing feature not supported is the fall-through feature of C's switch, in which, if you do not use a break statement at the end of one case, control "falls through" and executes the next case as well - with the same thing happening there if there is no break. Something like the default clause is supported - but not via that keyword.

A user may want to use this if they want to have something like C's switch in Python, instead of using a chain of if-elif-elif-...-else clauses, but without the fall-through option that C's switch has.

Note: This is experimental code, done more as a curiosity, not meant for production use, so use at your own risk.