How to handle switch case in Python.
Like many other programming languages python doesn't support switch case construct.
Official documentation says you can achieve the same thing with sequence of "if....elif...elif...else". However this can get pretty messy code if practice.
Let's look at the example below:
def get_car_color(car):
if car == 'ford':
return ['red', 'black', 'white', 'silver', 'gold']
elif car == 'audi':
return ['black', 'white']
elif car == 'volkswagen':
return ['purple', 'orange', 'green']
elif car == 'mercedes':
return ['black']
else:
return ['pink']
It's nice to see our little get_car_color
function. Now let's say after every few days the boss tells to add new car companies support to our function. Because of that we have to update our function and add more "elif...elif.." sequences.
As we add more cars to our function, code will become cumbersome and will not be pythonic.
Instead of writing multiple "...elif..." sequences we can use a dictionary store car name and supported colors.
Let's look at the example below:
car_name_and_colors = {
'ford': ['red', 'black', 'white', 'silver', 'gold'],
'audi': ['black', 'white'],
'volkswagon': ['purple', 'orange', 'green'],
'mercedes': ['black'],
}
def get_car_color(car):
return car_name_and_colors[car]
This made our code small and easy to read and maintain. But there is still one problem though. If you try to call get_car_color
with brand which is not in our dictionary, the method will give KeyError
.
So, switch cases require some default that will be used if any of the switch case is not matched. One way to overcome this is to call dictionary using .get method
.
.get method
allows us to specify default value. This default value will be used if KeyError occurs.
Code below we have modified the get_car_color
function:
def get_car_color(car):
return car_name_and_colors.get(car, 'pink')
So this is how we can write cleaner and more readable switch case workaround if sequence of 'if..elif..elif..else' get too long.
Hope you liked this article
There is one more elegant way to achieve the switch-case effect in Python, i.e., using the OOPs concept. You can write a switch class with the following pattern.
1- The switch class shall have a switcher function accepting the choice as an argument.
2- This function will call the getattr() method to map options to functions handling individual cases.
3- The getattr() also takes a default function argument which gets returned when there is no other matching function.
4- You also need to define handlers for every case.
9Apps Lucky Patcher VidMate
This is a good solution. One slight improvement is to use your initial solution, but simply add the dictionary K/V pair:
None : ['pink']
, and modify the function signature to be(car=None)
. This eliminates the exception while simultaneously leaving the function definition generic (i.e. not hard-coding in ‘pink’).car=None
is fine but it won’t solver the case where car value is notNone
Correct. In that case we want the tweak below.
Again the improvement being not to hardcode
'pink'
into the function, and instead let the dictionary (the data store) semantically define that finalelse
case just as it does theelif
cases (i.e. all in the same place). Because today it’s'[pink]'
, tomorrow it’s'[turquoise]'
or even'[pink, turquoise]'
. =:)