Part I. How Can We Switch?

Part I. How Can We Switch?

Unlike most programming languages, Python doesn?t have a built-in implementation of a switch statement. In general, a switch statement is to evaluate an expression or a variable against a list of values to check for equality. When the case matches the evaluation result or the variable, the corresponding operations will run under that case. When no case is found, the default operations will run instead.

Here?s an example of a switch statement in Swift. When we call this function with different characters, the operations for the matched case or the default run as expected.

Given no switch statements in Python, the present article is to show you how we can implement a switch-like functionality in Python. Specifically, the article consists of the following two parts, as implied by the article?s title.

  • Describe the approaches to ?switch?
  • Identify the best approach to ?switch?

?1. Use the if?elif?else statements

The first approach is very straightforward. We can simply use multiple if?elif? else statements to list all possible conditions such that the expression or variable can be evaluated against to these conditions. In the following figure, we write a Python function that is similar to the switch statement in Swift as shown at the beginning of the article.

Image for post

?2. Use the get() function with a dictionary

The second approach is to use a dictionary consisting of the key-value pairs that cover all known conditions. For the variable that we?re checking, we?ll use the get() function to retrieve the value of the key that matches the variable.

Image for post

It should be noted that we may want to supply the get() function with a default value when no key matches the variable. If a default value is not set, the returned value will be None of the NoneType, which should be handled differently from the presumably expected string type.

?3. Use a dictionary by checking the variable?s existence first

The third approach is similar to the above but has some slight differences. Let?s look at the code first.

Image for post

We will still use the same dictionary characters in [2] as the previous example. Instead of using the get() function, we first check if the variable character is one of the keys in the dictionary. If it is, we assign the key?s value to the temporary variable something, and if it?s not, we use the default value.

It may be wondered why we want to have this approach as it?s very similar to the previous one. We?ll talk about this in the second part.

?4. Use the defaultdict in the collections module

Another approach is to leverage the defaultdict class in the collections module. The following figure shows you how it works to make a ?switch? statement in Python.

Image for post

The difference of this approach from the previous couple is that it uses the defaultdict that takes a lambda to set the default value when a key doesn?t exist in the dictionary characters_with_default.

Part 2. What?s the Best Approach?

The first part lists the four approaches that we can use to perform the ?switch? functionality in Python. In this part, we will identify the best approach in terms of their operation speed, which will provide some guidance for our own Python coding.

To do that, we?ll first clean up all the code used before and assemble all needed variables and functions for the performance evaluation.

Image for post

As you may notice, overall they stay about the same, but I create another two functions create_characters() and create_characters_with_default(), which create the characters and characters_with_default dictionaries, respectively. These functions will be used to determine the time needed to create these dictionaries, as the operation time for initiating pertinent variables should also be considered to determine the best approach.

Image for post

Specifically, we use the magic method %timeit in jupyter to evaluate the function?s run time by averaging 100,000 times of operations to achieve a stable estimate of the operation speed.

In total, two sets of experiments were run. In [7], I used the character ?l? as the parameter for applicable functions, and we knew that ?l? is one of the conditions. By contrast, in [8], I used the character ?k? as the parameter, which is not one of the conditions.

In both sets, the ?4. approach involving the use of defaultdict had the best performance. However, it should be noted that to use this approach, we had to create the characters_with_default dictionary, which was a very time-consuming step.

Depending on whether the variable matches the list of conditions, the ?1. approach (i.e., using the if?elif?else statements) would outperform the ?2. and ?3. approaches when the variable matched one condition, while performed worse when the variable matched no listed conditions ? the worst case for the ?1. approach. It should be noted as well that to use the ?2. and ?3. approaches, we had to create the characters dictionary, the operation time of which was quite considerable.

As mentioned previously, ?2. and ?3. approaches were similar in its implementation logic. However, when the variable didn?t match any of the existing keys in the dictionary, the ?3. approach had better performance than the ?2. approach. The performance of the ?2. approach didn?t appear to differ when the variable did or didn?t match any of the dictionary?s keys.

Conclusions & Takeaways

Although Python has no native support for the switch statements, we can conveniently use the built-in dictionary to achieve the same functionality. However, these four approaches do have differential implementations and their performance speeds differ considerably. Thus, there is no one-size-fits-all approach to ?switch? in Python. Here?s a list that I created for your quick reference in terms of what approach is best in a defined scenario.

In the above table, the ?Possible Conditions? refers to how many conditions that we need to check, the ?Use Times? means how many times we need to call the ?switch? functionality, and the ?Recommendation? is based on the average performance speed as well as readability. Generally, a dictionary can be written in a way that has better readability of the if?elif?if statements.

Last but not the least, if you don?t know which one to use, just go ahead use the ?3. approach, which involves little overhead of constructing a dictionary and requires no extra modules.

18