Introduced in Python 3.10, amatch
statements, which are similar to those in other languages (eg: C, JAVA).switch
maybecase
statements, but more powerful. Here's an example of a statement that uses Python 3.10'smatch
Example of a statement:
def http_error(status): match status: case 400: return "Bad request" case 401 | 403 | 404: return "Not allowed" case 500: return "Server error" case _: return "Something's wrong with the internet" print(http_error(400)) # Output: Bad request print(http_error(401)) # Output: Not allowed print(http_error(500)) # Output: Server error print(http_error(600)) # exports: Something's wrong with the internet
In this example, thematch
statement willstatus
parameter is compared to a series of patterns. These modes can be single values such as400
maybe500
, or a combination of values such as401 | 403 | 404
. If there is no match, it will match to the wildcard character_
。
In addition.match
It can also be used for data structure deconstruction:
# Suppose we have a list of elements of different types def handle_items(items): match items: case []: print("No items.") case [first]: print(f"One item: {first}") case [first, second]: print(f"Two items: {first} and {second}") case [first, *rest]: print(f"First item: {first}, rest: {rest}") handle_items([]) # Output: No items. handle_items(["apple"]) # Output: One item: apple handle_items(["apple", "banana"]) # exports: Two items: apple and banana handle_items(["apple", "banana", "cherry"]) # Output: First item: apple, rest: ['banana', 'cherry']
In this example, thematch
statement checkingitems
list, different blocks of code are selected for execution depending on the length and content of the list.
match
Allows developers to write cleaner, more readable code that maps directly to data structures and conditions. This makes dealing with complex data structures, such as nested JSON or complex class instances, more intuitive and safer.
This article on the specific use of Python switch article is introduced to this, more related to the use of Python switch content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future!