The match
statement is a powerful addition to Python introduced in PEP 634, which aims to provide a more readable and concise alternative to complex if
…elif
…else
chains and nested switch
statements. This new feature enhances the code readability and maintainability, especially when dealing with multiple patterns and conditions. In this tutorial, we will explore the match
statement in-depth with explanations and examples.
Table of Contents
- Introduction to the
match
Statement - Basic Syntax of
match
- Pattern Matching Basics
- Match Case Expressions
- Using Constants and Patterns
- Combining Patterns
- Ignoring Values with
_
- Creating Custom Match Functions
- Python
match
vsif
…elif
…else
- Practical Examples
- Example 1: Matching Various Data Types
- Example 2: Simplifying Code with Nested Patterns
- Benefits and Drawbacks of
match
Statements - Conclusion
1. Introduction to the match
Statement
The match
statement in Python introduces a more concise and readable way to perform pattern matching on values. Pattern matching is a mechanism that allows you to test a value against a series of patterns and execute code based on which pattern matches the value.
Traditionally, in Python, this kind of pattern matching was often done using nested if
…elif
…else
statements or more complex data structures like dictionaries. While these methods work, they can become hard to read and maintain, especially when dealing with multiple patterns and conditions. The match
statement aims to address these issues.
2. Basic Syntax of match
The basic syntax of the match
statement is as follows:
match value:
pattern1:
# code to execute if pattern1 matches value
pattern2:
# code to execute if pattern2 matches value
# ...
patternN:
# code to execute if patternN matches value
_:
# code to execute if no patterns match
Here, value
is the expression you want to match against various patterns, and each pattern
is a valid pattern expression. The _
(underscore) at the end is a special pattern that acts as a catch-all for values that don’t match any of the preceding patterns.
3. Pattern Matching Basics
Pattern matching allows you to match values using various patterns, such as literals, variables, and more complex structures. Let’s start with some basic patterns:
- Matching a literal:
match color:
"red":
print("You chose red!")
"blue":
print("You chose blue!")
"green":
print("You chose green!")
_:
print("You chose an unknown color.")
- Matching a variable:
match age:
18:
print("You are now an adult!")
16:
print("Sweet sixteen!")
_:
print("Your age doesn't match any known patterns.")
4. Match Case Expressions
Each pattern inside a match
statement can be followed by a block of code to execute if that pattern matches the value. This is referred to as a “match case” expression. You can have multiple match cases within a single match
statement.
match day:
"Monday":
print("It's the start of the workweek.")
"Friday":
print("Weekend is near!")
"Saturday" or "Sunday":
print("It's the weekend!")
_:
print("It's a regular weekday.")
In this example, the third case demonstrates the use of multiple possible values within a single pattern.
5. Using Constants and Patterns
Patterns can also include constants, which are checked for equality with the value
. You can combine literals and variables within patterns:
match point:
(0, 0):
print("You're at the origin.")
(x, 0):
print(f"You're on the x-axis at {x} units.")
(0, y):
print(f"You're on the y-axis at {y} units.")
(x, y):
print(f"You're at point ({x}, {y}).")
6. Combining Patterns
You can combine patterns using the |
(pipe) operator, allowing you to match multiple patterns in a single case:
match value:
0 | None:
print("The value is zero or None.")
1 | 2 | 3:
print("The value is 1, 2, or 3.")
_:
print("The value doesn't match any known patterns.")
7. Ignoring Values with _
The _
(underscore) pattern is used to match any value and is often used as a catch-all when no other patterns match. It can also be used to ignore specific values:
match value:
"apple":
print("It's a delicious apple!")
"banana":
print("It's a ripe banana!")
_:
print("I don't recognize this fruit.")
8. Creating Custom Match Functions
You can create your own functions to use as patterns in a match
statement. These functions should return either True
or False
based on whether the value matches the pattern.
def is_even(x):
return x % 2 == 0
def is_positive(x):
return x > 0
match number:
is_even:
print("It's an even number.")
is_positive:
print("It's a positive number.")
_:
print("The number doesn't match any known patterns.")
9. Python match
vs if
…elif
…else
While the match
statement can make your code more concise and readable, there are cases where using traditional if
…elif
…else
statements might be more appropriate. Use match
when dealing with multiple patterns that involve the same value and when the patterns have a clear hierarchy.
10. Practical Examples
Example 1: Matching Various Data Types
def check_type(value):
match value:
str:
print("It's a string.")
int:
print("It's an integer.")
float:
print("It's a float.")
list:
print("It's a list.")
dict:
print("It's a dictionary.")
_:
print("It's a different data type.")
check_type("Hello")
check_type(42)
check_type(3.14)
check_type([1, 2, 3])
check_type({"key": "value"})
check_type(True)
Example 2: Simplifying Code with Nested Patterns
Consider a scenario where you need to categorize people based on age and gender.
def categorize_person(person):
match person:
("male", age) if age < 18:
print("Young boy")
("male", age) if age >= 18:
print("Gentleman")
("female",
age) if age < 18:
print("Young girl")
("female", age) if age >= 18:
print("Lady")
_:
print("Unknown category")
categorize_person(("male", 25))
categorize_person(("female", 15))
categorize_person(("nonbinary", 30))
11. Benefits and Drawbacks of match
Statements
Benefits
- Readability:
match
statements can greatly improve the readability of code, especially when dealing with multiple patterns and conditions. - Conciseness:
match
statements often result in more concise code compared to equivalentif
…elif
…else
structures. - Maintainability: As patterns are defined separately from the code to execute, maintenance becomes easier when patterns or conditions change.
Drawbacks
- Compatibility: The
match
statement is introduced in Python 3.10 and is not available in earlier versions. - Learning Curve: Developers familiar with traditional control structures may need time to adapt to the new syntax.
12. Conclusion
The match
statement is a powerful addition to Python that simplifies and enhances pattern matching in your code. By providing concise and readable syntax, the match
statement makes it easier to handle complex branching logic, resulting in more maintainable and elegant code. While it might take some time to adjust to the new syntax, the benefits in terms of code readability and maintainability are well worth the investment. As Python continues to evolve, the match
statement is sure to become an indispensable tool in every developer’s toolkit.