In this tutorial, we'll explore the match statement introduced in Python 3.10, which provides a powerful and flexible way to perform pattern matching. This feature is particularly useful for handling multiple conditions based on different patterns, making your code more readable and concise compared to traditional if-elif-else chains. Whether you're working with simple data types or complex objects, the match statement can simplify your control flow logic.
The match statement is a generalization of the switch statements found in other programming languages like C, Java, and JavaScript. It allows you to match a variable against multiple patterns and execute different blocks of code based on which pattern matches.
1match variable:2case pattern1:3# Code block for pattern14case pattern2:5# Code block for pattern26case _:7# Default case (wildcard)
match: The keyword used to start the match statement.variable: The expression to be matched against patterns.case: Used to specify a pattern to match._: A wildcard pattern that matches any value, similar to default in other languages.Let's start with a simple example where we match an integer against different cases.
1def match_number(n):2match n:3case 1:4return "One"5case 2:6return "Two"7case 3:8return "Three"9case _:10return "Other"1112print(match_number(1)) # Output: One13print(match_number(4)) # Output: Other
One Other
In this example, the function match_number takes an integer n and returns a string based on its value. The match statement checks each case in order until it finds a match or reaches the default case.
The underscore _ acts as a wildcard pattern, matching any value. It's often used to handle cases that don't require specific handling.
Here's an example where we use wildcards to handle multiple values in a single case.
1def match_letter(letter):2match letter:3case 'a' | 'e' | 'i' | 'o' | 'u':4return "Vowel"5case _:6return "Consonant"78print(match_letter('a')) # Output: Vowel9print(match_letter('b')) # Output: Consonant
Vowel Consonant
In this example, the match_letter function checks if a given letter is a vowel or consonant using a wildcard pattern to match any of the vowels.
Guard clauses allow you to add additional conditions within a case. These conditions are specified after an if keyword and must evaluate to True for the case to be executed.
Let's see how guard clauses can be used to refine pattern matching.
1def match_temperature(temp):2match temp:3case t if t < 0:4return "Freezing"5case t if 0 <= t < 20:6return "Cold"7case t if 20 <= t < 30:8return "Mild"9case t if 30 <= t < 40:10return "Warm"11case _:12return "Hot"1314print(match_temperature(-5)) # Output: Freezing15print(match_temperature(15)) # Output: Cold16print(match_temperature(25)) # Output: Mild17print(match_temperature(35)) # Output: Warm18print(match_temperature(45)) # Output: Hot
Freezing Cold Mild Warm Hot
In this example, the match_temperature function categorizes temperatures into different ranges using guard clauses. Each case checks a specific range and returns a corresponding description.
Class patterns allow you to match against instances of classes and extract their attributes. This is particularly useful for handling complex data structures like objects.
Let's see how class patterns can be used to match against custom objects.
1class Point:2def __init__(self, x, y):3self.x = x4self.y = y56def describe_point(p):7match p:8case Point(x=0, y=0):9return "Origin"10case Point(x=0, y=y):11return f"Y-axis at {y}"12case Point(x=x, y=0):13return f"X-axis at {x}"14case Point():15return f"Point at ({p.x}, {p.y})"16case _:17return "Not a point"1819print(describe_point(Point(0, 0))) # Output: Origin20print(describe_point(Point(0, 5))) # Output: Y-axis at 521print(describe_point(Point(3, 0))) # Output: X-axis at 322print(describe_point(Point(4, 7))) # Output: Point at (4, 7)
Origin Y-axis at 5 X-axis at 3 Point at (4, 7)
In this example, the describe_point function uses class patterns to match against instances of the Point class. It checks for specific points like the origin and axes, and provides a general description for other points.
Let's create a practical example that demonstrates the use of the match statement in a real-world scenario. We'll build a simple command-line tool that interprets user commands.
1def parse_command(command):2match command.split():3case ["start", service]:4return f"Starting {service}..."5case ["stop", service]:6return f"Stopping {service}..."7case ["restart", service]:8return f"Restarting {service}..."9case ["status"]:10return "Checking status..."11case _:12return "Unknown command"1314def main():15while True:16user_input = input("Enter a command: ")17if user_input.lower() == "exit":18break19print(parse_command(user_input))2021if __name__ == "__main__":22main()
This script defines a parse_command function that uses the match statement to interpret different commands. The main function runs an interactive loop where users can enter commands, and the program responds accordingly.
| Concept | Description |
|---|---|
| Basic Match Statement | Matches a variable against multiple patterns using case. |
| Wildcard Patterns | Uses _ to match any value. |
| Guard Clauses | Adds additional conditions within a case using if. |
| Class Patterns | Matches against instances of classes and extracts their attributes. |
match statement provides a cleaner and more readable way to handle multiple conditions compared to if-elif-else chains._) are useful for handling cases that don't require specific handling.In the next tutorial, we'll explore loops in Python, starting with the for loop. We'll learn how to use the range() function to generate sequences of numbers and apply them in various scenarios. This will build on our understanding of control flow and prepare us for more complex programming tasks.
Stay tuned!