Python Switch Case—Comprehensive Guide
Python switch-case statements are here! And they are actually called match-case statements.
This means you can soon replace this type of if-else mess:
With a more compact match-case statement:
In some situations, the latter approach is better. It can make the code more readable and less repetitive.
Notice that this becomes available in Python 3.10, which will be released early in October 2021.
In this guide, you learn everything you need to know about Python match-case statements.
The Problem with If-Else in General
Speaking of any programming language, if-else statements are not always the most effective way to make comparisons. This is true when the if-else statements are repetitive.
To see an example, let’s write a pseudocode script that checks the day of the week using if-else statements:
In this piece of code, there is a lot of repetition.
Each else-if check repeats
day == “something”.
However, it is clear we are referring to
day in each comparison. So it would be great if we did not need to repeat
day == “something”.
This gives rise to a neat solution called the switch-case statement.
The Solution—Switch Case Statements
The switch-case statement combines if-else statements into a single pattern-matching structure.
Using switch-case, you specify the value you are interested in and specify patterns (cases) for each possible outcome. The code then tries to match the value with the patterns.
Using a switch-case statement helps you avoid repetition and makes the code clean.
Here is a pseudocode example of replacing the above if-else mess with switch-case:
This looks way cleaner.
The switch-case is seen in popular programming languages, such as C++.
Python 3.10 also supports switch-case statements. But they go with a different name—match-case statements.
Match Case Statement—Python’s Version of Switch Case
Python versions of 3.10+ start supporting the switch-case statement. Notice how in Python, it is called match-case, not switch-case.
The match-case statement is also known as structural pattern matching.
The problem match-case solves is described in the previous chapter. In short, it replaces repetitive if-else statements with a compact pattern-matching structure.
Match Case in Python
The match-case statement follows this syntax:
match elementmeans “match the
elementwith the following patterns”
- Then each
case patternstatement compares the
elementwith the specified pattern. This can for example be a string or number.
- If a pattern matches with the
element, the corresponding block of code gets executed. After that, the match-case statement is exited.
Let’s implement the weekday pseudocode example in Python.
The regular if-else approach would look like this:
But with Python 3.10 match-case statement, you can prettify the code quite a bit:
By the way, you can (with multiple expressions you should) break the expressions to separate lines:
Now you have a basic understanding on what is structural pattern matching in Python. Let’s then jump into different pattern types you can match with.
Match Case Pattern Types
There are different types of patterns you can match with.
The most notable ones are:
- Literal patterns
- Capture patterns
- Wildcard patterns
- Constant value patterns
- Sequence patterns
Let’s go through each in detail.
The most basic use case for match cases is matching with literal patterns. The literal you can match with can be a:
A good example of literal pattern matching is the weekday example. In this example, we match a string literal with a variable
You can use the match-case statement to store (capture) a matched value to a variable.
This is best demonstrated with an example.
For example, let’s create a function
greet() that greets a person if a name is specified.
This match-case statement does two things (as highlighted in the comments):
- Checks if the
None. If it is, the default greeting is printed.
- Checks if the
namematches with something else than
None. If it does, that name is stored into
some_name. This name is then greeted.
When using match-case, you can use a wildcard pattern to match without binding. This is the “else” block of a match-case statement.
The wildcard pattern matches with a value that no other case is matching with.
To create a wildcard pattern, use the underscore
For example, let’s match for a result of a coin flip:
Must be 0 or 1.
Here the wildcard case matches with anything else than
Another use case for the wildcard is if you don’t care about the value of the match. This is useful when you want to make sure there is the value (or a group of values), regardless of what that value is.
For example, let’s check the dimension of a tuple that represents a location without caring about the coordinate values:
2D location found
As you can see, this match-case only cares about the number of elements found.
Constant Value Patterns—Enumerations and Match Case
You can use enumeration items as patterns in a match-case statement.
In case you are unfamiliar with enumerations, see this article.
To demonstrate how an enumeration and match-case statement can be used:
- Let’s create a
Directionenumeration that represents the four main directions in the compass.
- Let’s also create a function
handle_directions()that takes a direction as an input. This function matches the direction with one of the directions from the enumeration and reacts accordingly.
Here is the code:
Now you can call handle_directions() this way for example:
You could replace the above script with a much simpler one. But this demonstrates how you can use enumerations and match-case.
The reason why you may want to do this is that you don’t want to use so-called mystic strings in your code. For more details on what this means, see this article.
You can unpack the values of a sequence in pattern matching.
If you don’t know what unpacking is, it means pulling the values of a sequence into separate variables.
Here is an example:
You can use unpacking in pattern matching.
For example, let’s check if a location is a 1D, 2D, or 3D point. In addition, let’s store the coordinate values into separate variables and print them out.
2D location found: (1, 3)
The code matches
location with a tuple of one, two, or three elements. The coordinate values are then unpacked to separate variables.
If you have more values, but you care about the first three, you can use the * operator. This accounts for “the rest of the elements”.
For instance, let’s say you have a tuple
location that represents coordinates. In addition, it can store additional elements. To catch the extra items, let’s use the
3D location found: (1, 3, 2)
Also, there was some extra data: ['a', 'b', 'c']
*names captures all “the rest” of the elements in the
location tuple—no matter how many extra elements there are.
Now you know the basic pattern types you can match against.
Let’s finally take a look at how to combine patterns.
Combining Patterns in Match Case
It is possible to compare patterns in a match-case statement.
To do this, use the logical or operator
|. This checks if at least one pattern matches the value.
For example, let’s match days based on if they are weekends or not:
In programming, the switch-case statement is a replacement for repetitive if-else statements.
This feature will be unlocked in Python 3.10 in early Oct 2021. In Python, it goes with the name of match-case statement.
Here is an example of a match-case statement:
The match-case statement matches a value with a group of patterns. If there is a match, a piece of code is executed.
Match-case works similar to if-else statements. The main difference is you don’t need to repeat the name of the compared item.
Thanks for reading. I hope you find it useful.
Become a Top Coder
Did you like this article?
Become a member at Medium.com to read top stories by experts in the field.
Disclaimer: By joining via the provided link, I earn a small commission at no extra cost for you :)