Python:Match
"Structural Pattern Matching" 은 파이썬 3.10 부터 도입된 문법이다. match
~ case
문 이다.
Introduced in Python 3.10, Structural Pattern Matching gives Python developers a powerful alternative to traditional conditional logic.
- Unpacking
- Starred unpacking
- Partial assignment
- Class & Class attribute matching
- Complex pattern with wildcard
- Guard
Examples
At its most basic, the syntax looks like this:
match value:
case pattern1:
# code if value matches pattern1
case pattern2:
# code if value matches pattern2
case _:
# wildcard case (default)
The real power comes with destructuring! Match patterns break down complex data structures and extract values in a single step.
# Destructuring and matching tuples
match point:
case (0, 0):
return "Origin"
case (0, y):
return f"Y-axis at {y}"
case (x, 0):
return f"X-axis at {x}"
case (x, y):
return f"Point at ({x}, {y})"
# Using OR pattern (|) to match multiple patterns
match day:
case ("Monday"
| "Tuesday"
| "Wednesday"
| "Thursday"
| "Friday"):
return "Weekday"
case "Saturday" | "Sunday":
return "Weekend"
# Guard clauses with inline 'if' statements
match temperature:
case temp if temp < 0:
return "Freezing"
case temp if temp < 20:
return "Cold"
case temp if temp < 30:
return "Warm"
case _:
return "Hot"
# Capture entire collections using asterisk (*)
match numbers:
case [f]:
return f"First: {f}"
case [f, l]:
return f"First: {f}, Last: {l}"
case [f, *m, l]:
return f"First: {f}, Middle: {m}, Last: {l}"
case []:
return "Empty list"
You can also combine match-case with other Python features like walrus operators to create even more powerful patterns.
# Check if a packet is valid or not
packet: list[int] = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]
match packet:
case [c1, c2, *data, footer] if ( # Deconstruct packet into header, data, and footer
(checksum := c1 + c2) == sum(data) and # Check that the checksum is correct
len(data) == footer # Check that the data length is correct
):
print(f"Packet received: {data} (Checksum: {checksum})")
case [c1, c2, *data]: # Failure case where structure is correct but checksum is wrong
print(f"Packet received: {data} (Checksum Failed)")
case [_, *__]: # Failure case where packet is too short
print("Invalid packet length")
case []: # Failure case where packet is empty
print("Empty packet")
case _: # Failure case where packet is invalid
print("Invalid packet")
See also
Favorite site
- 8. Compound statements — Python 3.13.3 documentation
- How to do structural pattern matching in Python 3.10 with a type to match? - Stack Overflow
- Structural pattern matching in Python 3.10
- Structural Pattern Matching in Python – Real Python
- PEP 634 – Structural Pattern Matching: Specification | peps.python.org
- PEP 636 – Structural Pattern Matching: Tutorial | peps.python.org
- (Python) 파이썬 3.10 기능 소개 — 잡다한 AI 관련 글들