The power of the match statement in Python
python ·The match
statement has been added to the Python programming language since version 3.10 (in 2021).
Usually, you can find it as an alternative to the if-elif-else
statement. If so, why bother adding it to the set of Python’s statements? Let’s start with a comparison of the notation in an example where both statements do the same thing:
Up to now, the match
statement has not added anything new. Its true power comes when we use it with a concept called Algebraic Data Type.
Algebraic Data Type
An ADT is a disjoint union of tuples of types that could be mutually recursive. The advantage is when we read them, because given a type, the compiler/interpreter can be sure of its components. A drawback is that they are not extensible (with respect to classes).
Their idea is very similar to Enums
, with the improvement of being able to carry data alongside.
Usage in Python
For our example we consider the scenario where we have to send an instruction to a robot. The possible actions are:
- Go to the position P(x, y)
- Send a generic message M(text)
- Do nothing
if-elif-else
In the following listing, we check which type of actions we are handling and then retrieve the data we are interested in.
match-case
With the match
statement, the action type checking and the data retrieval are both performed by the case
clause.
Conclusion
As you can see, the use of the match statement allows for a cleaner way to handle multiple types of actions without the complexity of data retrieval. This is possible thanks to the match-case
statement, which is capable of “understanding” the different types of actions and creating “generic variables” on the go.