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.
Thanks for reading Daily Dose of Data Science! Subscribe for free to learn something new and insightful about Python and Data Science every day. Also, get a Free Data Science PDF (250+ pages) with 200+ tips.
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.