More Pattern Matching in Python 3.10 | by Alan Jones | Towards Data Science

Python has, at long last, got itself a switch statement. Hooray!
But it’s not your common or garden switch statement as you would find in C or Java — of course not, this is Python. Python 3.10 implements Structural Pattern Matching which can be as simple as a switch statement but can also be rather more.
I covered the basics of Structural Pattern Matching here — this article goes into the topic a bit further, looking at capturing matched patterns (getting the value of a match that could be more than one value) and adding conditions to patterns.
But, first, let’s revise the basics. Structural Matching Patterns are implemented with the match keyword. This encompasses a block that contains a list of case statement for each of the matches. You can see the syntax in the code below — it’s very neat and straightforward.
The code below runs a loop giving the values 1,2,3,4 and 5 to the variable quote. We define four cases, the first matches the numbers 1 or 4 (the | character is an OR operator); the second and third match 2 and 3 respectively and the last is the wildcard case that matches anything. Cases are processed in order so the wildcard is only matched if any of the preceding ones do not match. Also, unlike C, there is no ‘break’ statement — after the code block for each case is executed control is transferred to the end of the match.
for quote in [1,2,3,4,5]:    match quote:        case 1|4:            print("He's gone to meet his maker.")        case 2:            print("He should be pushing up the daisies.")        case 3:            print("He's shuffled off his mortal coil.")        case _:            print("This is a dead parrot!")
This is the result of running the code:
He's gone to meet his maker.He should be pushing up the daisies.He's shuffled off his mortal coil.He's gone to meet his maker.This is a dead parrot!
Sometimes, when we match an OR pattern we want to be able to use the matched value.
Let’s imagine some nerd, with incidental familiarity with Python, decided to represent a Monty Python script like this:
script = [["The Dead Parrot Sketch"],          ["Cast","Customer","Shop Owner"],          ["Customer","He's gone to meet his maker."],          ["Owner","Nah, he's resting."],          ["Customer","He should be pushing up the daisies."],          ["Owner", "He's pining for the fjords"],            ["Customer", "He's shuffled off his mortal coil."],          ["Customer", "This is a dead parrot!"]]
It’s a list of lists. The first one contain a single string — the title. The second, the cast which is the string “Cast” followed by a number of other strings representing the dramatis personae. The rest are lists of two strings, the cast member and the line that he or she should speak.
No prizes for data design, here.
How do we interpret this structure? The title is matched easily because it is the only single string. The cast is matched by specifying a list beginning with the string “Cast” and followed by a number of other elements (*actors does this). The lines of the script are matched by the last case: it matches two elements, the first is either “Customer” or “Owner” and the second is line which will capture the line of the script. The problem is that we want to use the value of “Customer” or “Owner” in the following code so we bind it to the variable person using the as keyword.
for line in script:    match line:        case [title]:            print(title)        case ["Cast",*actors]:            print("Cast:")            for a in actors: print(a)            print("---")        case [("Customer"|"Owner") as person, line] :            print(f"{person}: {line}")
Running the code we get this:
The Dead Parrot SketchCast:CustomerShop Owner---Customer: He's gone to meet his maker.Owner: Nah, he's resting.Customer: He should be pushing up the daisies.Owner: He's pining for the fjordsCustomer: He's shuffled off his mortal coil.Customer: This is a dead parrot!
This the case where we want to create match on condition that certain criteria are met. Look at the code below: we have a list of Harry Potter characters and a list of characters from Hitchhiker’s Guide to the Galaxy.
We ask for a name to be input and then try and match that name.
harrypotter = ["Harry","Hermione","Ron"]hhgtg = ["Arthur","Ford","Zaphod","Trillian"]name = input("Enter a name: ")match name:    case n if n in hhgtg:        print(f"{n} is a character in Hitchhiker's guide to the Galaxy.")    case n if n in harrypotter:        print(f"{n} is a character in the Harry Potter stories.")    case _:        print(f"{n} is an unknown character.")
And using the the construction:
case <match> if <match> in <list> 
we only match a case if it meets the condition that the string we want to match is in the list. The code is quite self-explanatory, I think, so here is the result of a few runs of the program.
Enter a name: HarryHarry is a character in the Harry Potter stories.Enter a name: ZaphodZaphod is a character in Hitchhiker's guide to the Galaxy.Enter a name: Elizabeth BennetElizabeth Bennet is an unknown character.
The last case is of course the wild card which will match anything that is not previously dealt with.
To learn even more go to the Python.org web site and read PEP 636, which is a tutorial on Structural Pattern Matching.
And to find out more about the new features in Python 3.10, you could take a look at other Medium articles such as James Briggs’s New Features in Python 3.10 or or Martin Heinz’s All The Important Features and Changes in Python 3.10.
As, I mentioned in my previous article, you should not be using Python 3.10 in earnest, yet, because it is still a beta release but that beta is downloadable from the Python website should you want to play around with it.