What is Pattern Matching
Pattern matching is a newer feature that came with Python 3.10. Using pattern matching simplifies the code and improves readability. The other option is to write multiple if-else statements, but this can quickly become very unreadable.
Example
Consider these 2 examples. The first one using multiple if-else statements, the second one pattern matching - match/case.
Which one is more readable?
|
|
|
|
This is a very simple example, and pattern matching can be also used in more complex situations where more conditions need to be met.
My use-case
I have recently built for myself a simple workout generator with Django. I used pattern matching to query the database based on selected difficulty. This is also a very simple use case, but I believe it makes the code readable, and it’s pretty clear what is going on.
|
|