Just a few days ago (October 4, 2021), Python released version 3.10. Looking at some of the features of the release, one of the most notable is structural pattern matching. That’s what you know as switch-case, sorry, match-case.

Here is the simplest match-case example. Doesn’t it look very straightforward?

def http_error(status) :
    match status:
        case 400:
            print("Bad request")
        case 404:
            print("Not found")
        case 418:
            print("I'm a teapot")
        case _:
            print("Something's wrong with the internet")
Copy the code

Full of expectation for this feature, I immediately downloaded and upgraded Python 3.10 to try it out. However, after my in-depth experience, I changed from expectation at the beginning to awe.

Awe is because such a seemingly simple new function has a lot of learning costs, and for those who know half of structural pattern matching, it will increase the probability of code error, which is not easily controlled by most people.

Why do I say that? I will summarize my views at the end of the article.

Since most of you haven’t actually used this structural pattern matching, I’ll start with update 3.10 to show you how to experiment with this new feature, and then I’ll go into the details of how to use match-case.

1. Upgrade 3.10

The current Version of Python on my local computer is 3.9.1

$ /usr/local/bin/python3 --version
Python 3.9.1
Copy the code

Since I am using a MAC here, I downloaded the PKG file of Python 3.10 from the official website. If you are a Win user, you can download the corresponding MSI or EXE file.

Download link I posted below, you can directly access the download

MAC: https://www.python.org/ftp/python/3.10.0/python-3.10.0-macos11.pkg win: https://www.python.org/ftp/python/3.10.0/python-3.10.0-amd64.exeCopy the code

After DOWNLOADING the installation file, I double-click install and then double-click the downloaded PKG file to enter the installation process

Click Continue all the way. If the user agrees, the installation is successful if the following message is displayed.

Check whether the upgrade is successful on the terminal

2. Use of OR mode

I’ve posted a simple example of match-case above, so I’ll skip the simple example and talk about some of the more specific uses.

In Python 3.10 there are a new type of joint operators |, but this can only be used for types, specific usage, I will do in detail in the next article, this article is focused on the match – the use of the case.

During the match – a case study, you will find that there is also a joint type is similar to the use of the operator, but please pay attention to the distinction, it is not the type of joint operations, but under the match – case unique operator | the or model, it can be more specific case statement abbreviated as the same of the same logic

match status:
    case 401 | 403 | 404:
        print("Not allowed")
    case _:
        print("Something's wrong with the internet")
Copy the code

3. The wildcard matches any object

Match-case is good for readability and makes your code more elegant, but there are some barriers to using it well, especially with wildcards.

Let me give you some examples

In the following code, the wildcard _ and the * symbol in mutable arguments are used

import sys

match sys.argv[1:]:
    case ["quit"] :print("exit")
    case ["create", user]:     Create a single user
        print("create", user)
    case ["create", *users]:  Create multiple users in batches
        for user in users:
            print("create", user)
    case _:
        print("Sorry, I couldn't understand the argv")
Copy the code

The _ in the last case is not a variable name, but represents a special pattern that is the last guarantee of a hit if none of the previous cases are missed. It is equivalent to the default branch of Go.

import "fmt"

func main(a) {
    education := "Undergraduate"

    switch education {
    case "博士":
        fmt.Println("I am the Doctor.")
    case "Graduate student":
        fmt.Println("I'm a graduate student")
    case "Undergraduate":
        fmt.Println("I'm an undergraduate.")
    case "College":
        fmt.Println("I'm a college student.")
    default:
        fmt.Println("Academic qualifications not up to standard...")}}Copy the code

4. Use the variable argument *args

The second case is very similar to the third case, except that the third case uses * before users, which is the same as the variable arguments in Python functions, and matches multiple values in the list.

In this command, users can be created in batches from command line parameters.

In a match-case, a variable will be created if the corresponding case is run. Such as

5. Use variable parameter ** KV

In the following code, ** REST matches keys and values in all args

6. Matching method of length

If you want to use case to only match the length of the object, you can use the following method

  • [* _]Matches any lengthlist;
  • * _) (_, _,Matches at least length 2tuple.

7. Matching of class objects

For matching class objects, the following example is simple enough not to be covered.

8. Match in order

Having covered the basics of match-case, read pep 636 for more details.

At the beginning of this article, I said that developers should be in awe of these new features. Match-case is a seemingly simple new feature, but it has a lot of learning costs. For those who know half a thing or two about structural pattern matching, it may increase the probability of code errors, which is not easy for most people to handle.

The reason for this is that match-case matches different objects according to different rules.

  • When a match object is a list or tuple, both the length and the element value need to match in order to make a match, which is why the following example uses the third case instead of the second.

  • When the object of a match is a dict, the rule is different. If the key in the case expression exists in the object of the match, the match can be matched.

  • When the object of a match is a class object, the matching rule is similar to that of a dict, as long as the object type and object properties meet the case conditions, the match can be made.

So when you’re writing match-case, probably the biggest challenge is figuring out how to do that order so that your code doesn’t flip over.

I personally summed up some rules, only for your reference:

  • List or tuple: Should go from unformatted to strict
  • Dict or Object: Strict to not strict

After half a day of testing, I have some understanding and share it with you. I don’t know if there is any problem with my understanding, but I still suggest that you should fully understand the matching rules of match-case before using it.

In addition, once the feature was introduced, many people said it was finally coming, while others said it was too weak.

My view on this is that match-case must have some application, but that doesn’t mean match-case is necessary. All match-cases can be replaced with if expressions, but not the other way around. If can combine AND and or to undertake n complex combination judgments, but match-case does not work. It can only be used for matching judgments of a single object.

But to some extent, it’s a bit redundant, and there’s an upstart cost.

So for such a new feature, would you use it?


At the end of this article, I will introduce three online documents written by myself:

The first document: PyCharm Chinese Guide 1.0 document

It took me more than two months to sort out the 100 Tips of PyCharm. In order for beginners to be able to use it directly, I spent a lot of time to record hundreds of GIFs and read online documents for those who are interested.

Second document: PyCharm Dark Magic Guide 1.0 document

The system includes a variety of cold Python knowledge, Python Shell diverse gameplay, crazy Python skills, Python super detailed advanced knowledge interpretation, very practical Python development skills.

Third document: The Python Chinese Guide 1.0 document

It takes three months to write a full Chinese tutorial for beginners to get started with Python, with a large number of code examples, so that beginners can have a visual experience of the operation of the code. The tutorials are both in-depth and extensive, and each article is marked with difficulty, whether it is basic or advanced. Python is a rare electronic tutorial in Python Chinese.