Rejoice! Gone are the long chains of if
…else
statements, because switch
statements will soon be here — sort of. What the Python gods are actually giving us are match
statements. match
statements are awfully similar to switch
statements, but have a few really cool and unique features, which I’ll attempt to illustrate below.
Flip The Switch
A switch
statement is often used in place of an if
…else
ladder. Here’s a quick example of the same logic in C, first executed with an if
statement, and then with a switch
statement:
Essentially, a switch
statement takes a variable and tests it for equality against a number of different cases. If none of the cases match, then the default
case is invoked. Notice in the example that each case
is terminated by a break
. This protects against more than one case matching (or allows for cascading), as the cases are checked in the order in which they are listed. Once a case is completed, break
is called and the switch
statement exits.
A Match Made In Heaven
You can think of match
statements as “Switch 2.0”. Before we get into the nitty-gritty here, if all you want is switch
in Python then you’re in luck, because they can be used in the same way. Here’s a similar example to what we looked at earlier, this time using match
in Python.
There are a few differences to note right off the bat. First, there are no break
statements. The developers were concerned about confusion if a break
statement were called inside a match
statement inside a loop — what breaks then, the loop or the match? Here, the first case that is satisfied is executed, and the statement returns. You’ll also notice that rather than default
, we have case _
, which behaves in the same way.
The Power of Pattern Matching
So, we’ve got a switch
statement with slightly different syntax, right? Not quite. The name match
was used for a reason — what’s actually going on here is something called Pattern Matching. To illustrate what that is, let’s look at a more exciting example, right out of the feature proposal to add the keyword in question to Python:
Wow! We just took an object, checked its type, checked it’s shape, and instantiated a new object without any indexing, or even a len()
call. It also works on any type, unlike the classic switch
which only works on integral values. In case this wasn’t cool enough for you, patterns can be combined. Again, from the feature proposal:
<img data-attachment-id="468671" data-permalink="https://hackaday.com/2021/04/02/python-will-soon-support-switch-statements/code_example_3/" data-orig-file="https://hackaday.com/wp-content/uploads/2021/03/code_example_3.png" data-orig-size="600,320" data-comments-opened="1" data-image-meta='{"aperture":"0","credit":"","camera":"","caption":"","created_timestamp":"0","copyright":"","focal_length":"0","iso":"0","shutter_speed":"0","title":"","orientation":"0"}' …read more
Source:: Hackaday