Python 3.10’s Match/Case Statement

I finally found a use case for python 3.10's new match/case statement. (I just wanted to try it out.) The use case is a trivial one; I’m just using it to pick between different print() statements about the number of results, based on match len(results).

match/case is snazzy, and it's more powerful than conventional switch implementations where the case values must be str/int/float/bool literals, since it can match tuple/list values. It’s able to load all or part of the comparison value into a variable. Also, when you need a switch statement (or something like it), you really need a switch statement (or something like it).

But use cases for match/case don't come along every day, either, and there's other forms that long if/elif/elif/&c. chains can take that it won't help you with. (For example, use a variable in a case clause and python will try to load part or all of the match comparison value into it; like switch in Java you can’t compare against variables.) All the same it's a neat addition to the language.

13 March 2023

Previous
Previous

Where Python 3.10’s := Operator Can Be Used

Next
Next

Using R for the First Time in Awhile