#312: Switch Statement in Python
For a long time, there was no switch/case statement in Python. Instead, we had to use a cascade of if/elif/else to filter for the different cases. But with Python 3.10 that changed and now we can use match / case to save us some typing. Let us see how this works.
Structural Pattern Matching
PEP 634 brought us structural pattern matching to Python and works like the well-known switch statement in other languages. The syntax looks like this:
The _ is for the default case, when nothing else matches. If we skip that part and run it with a value that has no matching case filter, then nothing happens.
A basic example
As a first example, we can take the code from the official documentation and make this little HTTP status to text translator:
If we run the code, we get this output:
Check for multiple values
We can check for multiple values in the same case statement by using the | operator:
This gives us the same text back for the 3 different values:
Logic in the case statement
We can use if statements in our case statement and create a more generic filter to match the right case:
The variable we used in our case statement stays around and we can access it in the code that runs if we have a match:
Matching dictionaries
We can pass a dictionary down to our match / case statement and filter on different values inside the dictionary:
Depending on what is in the dictionary, we run a different case statement:
Destructuring Sequences
If we have sequences like lists or tuples, we can unpack them on the go and check for a certain number of values:
Depending on our input, we can parse our coordinates into points:
Conclusion
Having a switch statement in Python in the form of match / case is a great help. Not only does it save us from a long cascade of if/elif/else, but it also allows us to get a lot of work done without writing many lines of code. Checking for parts of directories or taking sequences apart is a massive help when we have to deal with such cases. Try it!