In Defense of Match-case Statements in Python
I recently came across Khuyen Tran's post on š¦šššš”-ššš¬š in Python. In a gist, starting Python 3.10, you can use š¦šššš”-ššš¬š statements to mimic the behavior of š¢š-šš„š¬š.
Many responses on that post suggested that š¢š-šš„š¬š offers higher elegance and readability. Here's an example in defense of š¦šššš”-ššš¬š.
While if-else is traditionally accepted, it also comes with many downsides. For instance, many-a-times, one has to write complex chains of nested if-else statements. This includes multiple calls to š„šš§(), š¢š¬š¢š§š¬ššš§šš() methods, etc.
Furthermore, with š¢š-šš„š¬š, one has to explicitly destructure the data to extract values. This makes your code inelegant and messy.
Match-case, on the other hand, offers Structural Pattern Matching which makes this simple and concise. In the example above, match-case automatically handles type-matching, length check, and variable unpacking.
Share this post on LinkedIn: Post Link.
Read more here: Python Docs.
I like to explore, experiment and write about data science concepts and tools. You can read my articles on Medium. Also, you can connect with me on LinkedIn.