# Switch statement the pythonic way
Python does not have Switch statement, so If you got the following:
if cond == 'cond_a':
handle_a()
elif cond == "cond_b':
handle_b()
else:
handle_default()
Do this instead
func_dict = {
'cond_a': handle_a,
'cond_b': handle_b,
}
# Example call
cond = 'cond_a'
func_dict[cond]() # If you 'cond' exist, KeyError will raise for 'else:' statement.
# Workaround is to use the get() method and the handle_default() is address if 'cond' is not found.
func_dict.get(cond, handle_default)()
Complete example but with issues for production-grade performance
def dispatch_dict(operator, x, y):
return {
'add': lamba: x + y,
'sub': lamba: x - y,
'mul': lamba: x * y,
'div': lamba: x / y,
}.get(operator, lamba: None)()
Non-lambda appoarch
def go(operator):
calculator_actions = {
'add': do_add,
'sub': do_subtract,
'mul': do_multiple,
'div': do_divide,
}
if operator in calculator_actions:
x = 4
y = 2
sum = calculator_actions[operator](x, y)
print(sum)
def do_add(x, y):
return x + y
def do_subtract(x, y):
return x - y
def do_multiple(x, y):
return x * y
def do_divide(x, y):
return x / y
if __name__ == '__main__':
go(operator='add')
go(operator='sub')
go(operator='mul')
go(operator='div')
# Key-Takeway:
- This techinique has an issue for production-grade.
dispatch_dict
is created in memory with lambdas opcode lookup. - For production-grade, create the dictionary as constant and then reference it when the function is called.
- Rule of thumb, if
if-elif-else
goes over 3 conditions this switch statement as function could make your code Pythonic but understand the performance impact.