Just a few days ago (October 4, 2021) Python finally officially released version 3.10. After looking at some of the features of this version, the most concerned one should be structural pattern matching , right? It is the familiar switch-case , which is wrong, sorry, it is match-case.
Below is the simplest match-case example. Does it look very intuitive and concise?
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")
Looking forward to this feature, I quickly downloaded and upgraded Python 3.10 to try it out, but I didn't expect that after my in-depth experience, my anticipation from the very beginning turned into awe.
awe of because such a seemingly simple new function has a lot of learning costs, and for half-knowledge of the 16162fffdb8f24 structure pattern matching 16162fffdb8f25, it will increase the probability of code errors, which is not great Several people can easily control it.
Why would I say that? I will briefly describe my views at the end of the article.
Since most people have not actually used this structural pattern matching , I will teach you how to try this new feature from the upgrade 3.10, and then I will introduce the use of match-case in detail.
1. Upgrade to the new version 3.10
The current Python version on my local computer is 3.9.1
$ /usr/local/bin/python3 --version
Python 3.9.1
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.
I posted the download link 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.exe
After I downloaded the installation file, I double-clicked to install, and then I double-clicked the downloaded pkg file to enter the installation process
Click to continue all the way, agree to the agreement, and the following prompt appears to indicate that the installation is successful.
Confirm again on the terminal whether the upgrade is successful
2. Use of or mode
I have posted the simplest example of match-case above. I will skip the simple example and talk about the more special usages.
In Python 3.10, there is actually a new union type operator |
, but this can only be used for types. For specific usage, I will give a detailed introduction in the next article. This article will still focus on the use of match-case .
When learning match-case, you will find that there is also a usage similar to the union type operator, but please pay attention to the difference. It is not a union type operation, but the unique or mode under match-case Operator |
, it can abbreviate multiple case statements with the same logic into one
match status:
case 401 | 403 | 404:
print("Not allowed")
case _:
print("Something's wrong with the internet")
3. Wildcard matches any object
The emergence of match-case is conducive to improving the readability of the code and making your code more elegant, but at the same time, there are some thresholds to use it well, especially the use of wildcards.
Let me give some examples to explain
In the following code, the wildcard _
*
symbol in the variable parameter are used
import sys
match sys.argv[1:]:
case ["quit"]:
print("exit")
case ["create", user]: # 创建单个用户
print("create", user)
case ["create", *users]: # 批量创建多个用户
for user in users:
print("create", user)
case _:
print("Sorry, I couldn't understand the argv")
_
in the last case is not used as a variable name, but represents a special pattern. In the case of a miss in the previous case, this case will be the last guarantee to ensure a hit. It is equivalent to the Go language The default
branch.
import "fmt"
func main() {
education := "本科"
switch education {
case "博士":
fmt.Println("我是博士")
case "研究生":
fmt.Println("我是研究生")
case "本科":
fmt.Println("我是本科生")
case "大专":
fmt.Println("我是大专生")
default:
fmt.Println("学历未达标..")
}
}
4. Use variable parameters *args
The second case is very similar to the third case. The difference is that in the third case, users
added before *
. It is the same usage as the variable parameter in the original Python function, which will match multiple values in the list.
It means that users can be created in batches from the command line parameters.
If the corresponding case is run in the match-case, the corresponding variable will be created. for example
5. Use variable parameters **kv
In the following code, **rest
will match the key and value in all args
6. Length matching method
If you want to use case to match only the length of the object, you can use the following method
[*_]
match of any lengthlist
;(_, _, *_)
match length of at least 2tuple
.
7. Matching of class objects
For the matching of class objects, the following example is simple enough and will not be explained.
8. Pay attention to the order of matching
I have basically introduced the use of match-case above. If you need more detailed content, it is better to read through pep 636 .
When the beginning of the article, I said that developers should these new features awe , match-Case such a seemingly simple new feature, but it has a lot of learning costs, if structure pattern matching For people with half-knowledge, it may increase the probability of code errors, which is not easy for most people to manage.
The reason why I say this is because match-case faces different objects, and its matching rules are also different.
- When the object of match is a list or tuple, both the length and the element value need to be matched in order to be hit. This is why the following example takes the third case instead of the second case.
- When the object of match is a dict, the rules are different. As long as the key in the case expression exists in the object to be matched, it can hit.
- When the object of match is a class object, the matching rule is similar to dict. As long as the object type and the properties of the object meet the conditions of the case, the match can be hit.
Therefore, when writing a match-case, the biggest difficulty may be how to grasp this order in order to ensure that the code you write will not roll over.
I personally summarize some rules for your reference only:
- list or tuple: should never be formatted to strict
- dict or object: should be from strict to non-strict
After half a day of early adopters, I have some of their own understanding, for everyone to share, not sure I understand there is no problem, but I still suggest that you fully aware of match-case matching rules later, again to use it.
In addition, when this feature came out, many people said that finally came , and some people said that too tasteless. .
My opinion on this matter is that match-case must have certain applicable scenarios, but this does not mean that match-case is necessary. All match-case can be replaced with if expressions, but the reverse is not true. It is possible to combine and and or to undertake n multiple complex combinations of judgments, but match-case cannot. It can only be used for matching judgments for a single object.
But to a certain extent, it is a bit redundant and has a certain cost to get started.
So for such a new feature, would you use it?
At the end of the article, I will introduce to you three online documents written by myself:
first document : PyCharm Chinese Guide 1.0 Document
It took more than two months to sort out 100 PyCharm tips. In order to let novices get started directly, I spent a lot of time recording hundreds of GIFs, and I am interested in reading online documents.
second document : PyCharm Black Magic Guide 1.0 Document
The system includes a variety of Python unpopular knowledge, Python Shell's diverse gameplay, crazy Python dazzling technical operations, Python's ultra-detailed advanced knowledge interpretation, very practical Python development skills, etc.
third document : Python Chinese Guide 1.0 Document
It took three months to write a full Chinese tutorial suitable for zero-based introductory Python, with a large number of code cases, so that beginners have an intuitive feeling about the operation of the code. The tutorial has both depth and breadth. Each article The difficulty of the content of the Metropolis standard, basic or advanced, for readers to choose, is a rare Python Chinese electronic tutorial.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。