Python match Statement
matchis a structural pattern matching statement introduced in Python 3.10, similar to that in other languagesswitch-case, but more powerful.
The match statement can match patterns in data structures; not only constant values, but also complex patterns such as types, sequences, dictionaries.
Word Meaning: matchMeans "to match", used for pattern matching.
Basic Syntax and Parameters
The match statement is a new feature in Python 3.10+, used to replace complex multi-branch if-elif structures.
Syntax Format
match 变量:
case 模式1:
代码块1
case 模式2:
代码块2
case _:
默认代码块
Pattern Types
- Constant pattern: matches a specific value.
- Wildcard pattern:
case _Matches any value, equivalent to default. - Type pattern: matches data types.
- Sequence pattern: matches sequences such as lists, tuples.
- Dictionary pattern: matches dictionaries.
- Pattern with conditions: use
ifto add extra conditions.
Examples
Example 1: Basic Usage (Similar to switch)
Example
# Python version requirement 3.10+
def http_status(status):
match status:
case 200:
return "OK"
case 404:
return "Not Found"
case 500:
return "Server Error"
case _:
return "Unknown"
print(http_status(200)) # Output: OK
print(http_status(404)) # Output: Not Found
print(http_status(999)) # Output: Unknown
def http_status(status):
match status:
case 200:
return "OK"
case 404:
return "Not Found"
case 500:
return "Server Error"
case _:
return "Unknown"
print(http_status(200)) # Output: OK
print(http_status(404)) # Output: Not Found
print(http_status(999)) # Output: Unknown
Expected output:
OK Not Found Unknown
Code analysis:
case _is a wildcard that matches all unmatched cases.- Similar to default in switch-case.
Example 2: Multi-value Matching
Example
# Multiple values match the same result
def color_name(code):
match code:
case "r" | "R":
return "red"
case "g" | "G":
return "green"
case "b" | "B":
return "blue"
case _:
return "unknown"
print(color_name("r")) # Output: red
print(color_name("G")) # Output: green
print(color_name("x")) # Output: unknown
[/mycode]</div>
</div>
<p><strong>Expected output:</strong></p>
<pre>red
green
unknown
</pre>
<p>Using<code>|</code>can combine multiple values into the same case.</p>
<h3>Example3: Sequence Pattern Matching</h3>
<div class="example">
<h2 class="example">Example</h2>
<div class="example_code">[mycode4 type="python"]
# Sequence pattern matching
def describe_point(point):
match point:
case (0, 0):
return "origin"
case (x, 0):
return f"Point on the X-axis ({x}, 0)"
case (0, y):
return f"Point on the Y-axis (0, {y})"
case (x, y):
return f"Point on the plane ({x}, {y})"
case _:
return "invalid coordinates"
print(describe_point((0, 0))) # Output: origin
print(describe_point((5, 0))) # Output: Point on the X-axis (5, 0)
print(describe_point((3, 4))) # Output: Point on the plane (3, 4)
def color_name(code):
match code:
case "r" | "R":
return "red"
case "g" | "G":
return "green"
case "b" | "B":
return "blue"
case _:
return "unknown"
print(color_name("r")) # Output: red
print(color_name("G")) # Output: green
print(color_name("x")) # Output: unknown
[/mycode]</div>
</div>
<p><strong>Expected output:</strong></p>
<pre>red
green
unknown
</pre>
<p>Using<code>|</code>can combine multiple values into the same case.</p>
<h3>Example3: Sequence Pattern Matching</h3>
<div class="example">
<h2 class="example">Example</h2>
<div class="example_code">[mycode4 type="python"]
# Sequence pattern matching
def describe_point(point):
match point:
case (0, 0):
return "origin"
case (x, 0):
return f"Point on the X-axis ({x}, 0)"
case (0, y):
return f"Point on the Y-axis (0, {y})"
case (x, y):
return f"Point on the plane ({x}, {y})"
case _:
return "invalid coordinates"
print(describe_point((0, 0))) # Output: origin
print(describe_point((5, 0))) # Output: Point on the X-axis (5, 0)
print(describe_point((3, 4))) # Output: Point on the plane (3, 4)
Expected output:
原点 X轴上的点 (5, 0) 平面上的点 (3, 4)
match can destructure tuples/lists and extract values from them.
Example 4: Dictionary Pattern Matching
Example
# Dictionary pattern matching
def process_user(user):
match user:
case {"name": name, "age": age}:
return f"User: {name}, Age: {age}"
case {"name": name}:
return f"User: {name}"
case _:
return "invalid user"
print(process_user({"name": "Tom", "age": 20}))
print(process_user({"name": "Jerry"}))
print(process_user({"role": "admin"}))
def process_user(user):
match user:
case {"name": name, "age": age}:
return f"User: {name}, Age: {age}"
case {"name": name}:
return f"User: {name}"
case _:
return "invalid user"
print(process_user({"name": "Tom", "age": 20}))
print(process_user({"name": "Jerry"}))
print(process_user({"role": "admin"}))
Expected output:
User: Tom, 年龄: 20 User: Jerry 无效用户
Dictionary patterns can extract values of specific keys.
Example 5: Patterns with Conditions
Example
# Pattern matching with conditions
def classify_number(n):
match n:
case n if n > 0:
return f"positive number ({n})"
case n if n < 0:
return f"negative number ({n})"
case 0:
return "zero"
print(classify_number(10)) # Output: positive number (10)
print(classify_number(-5)) # Output: negative number (-5)
print(classify_number(0)) # Output: zero
# Complex conditions
def describe_list(lst):
match lst:
case []:
return "empty list"
case [x]:
return f"single element: {x}"
case [x, y]:
return f"two elements: {x}, {y}"
case [x, *rest]:
return f"first: {x}, rest: {rest}"
print(describe_list([]))
print(describe_list([1]))
print(describe_list([1, 2, 3, 4]))
def classify_number(n):
match n:
case n if n > 0:
return f"positive number ({n})"
case n if n < 0:
return f"negative number ({n})"
case 0:
return "zero"
print(classify_number(10)) # Output: positive number (10)
print(classify_number(-5)) # Output: negative number (-5)
print(classify_number(0)) # Output: zero
# Complex conditions
def describe_list(lst):
match lst:
case []:
return "empty list"
case [x]:
return f"single element: {x}"
case [x, y]:
return f"two elements: {x}, {y}"
case [x, *rest]:
return f"first: {x}, rest: {rest}"
print(describe_list([]))
print(describe_list([1]))
print(describe_list([1, 2, 3, 4]))
Expected output:
正数 (10) 负数 (-5) 零 空列表 单个元素: 1 第一个: 1, 其余: [2, 3, 4]
Usingcase 变量 if 条件can add extra matching conditions.
Other Extensions
Python3 Conditional Control