Sobes.tech
Junior

What are match/case constructs in Python?

sobes.tech AI

Answer from AI

The match/case constructions in Python, introduced in version 3.10, provide a mechanism for structural pattern matching. This allows comparing the value of an expression against a list of patterns and executing the code block corresponding to the first matching pattern.

Main elements:

  • match: A keyword that introduces the matching block. It is followed by an expression whose value will be matched.
  • case: A keyword to define a pattern. It is followed by the pattern itself. If the value of the expression from match matches the pattern from case, the code inside that case block is executed.
  • Patterns: Can be simple literals (numbers, strings, boolean values), named constants, lists, tuples, dictionaries with a specific structure, as well as include capturing variables (which capture matched parts of the value) and guard conditions (using if).

Example of basic usage:

// Function that returns an HTTP status description
def get_http_status_description(status_code):
    match status_code:
        case 200:
            return "OK"
        case 404:
            return "Not Found"
        case 500:
            return "Internal Server Error"
        case _: // Wildcard pattern - matches any value
            return "Unknown Status"

// Using the function
print(get_http_status_description(200))
print(get_http_status_description(404))
print(get_http_status_description(999))

Example of matching with composite structures and capturing variables:

// Example data (tuple or list)
point = (1, 2)
command = ["move", 10, 20]
user_data = {"name": "Alice", "age": 30}

// Matching with a tuple
match point:
    case (x, y):
        // x and y capture values from the tuple
        print(f"Point coordinates: x={x}, y={y}")

// Matching with a list
match command:
    case ["move", dx, dy]:
        // dx and dy capture values from the list
        print(f"Move by dx={dx}, dy={dy}")
    case ["wait", time]:
        print(f"Wait for {time} seconds")
    case _:
        print("Unknown command")

// Matching with a dictionary
match user_data:
    case {"name": name, "age": age}:
        // name and age capture values from the dictionary
        print(f"User: {name}, Age: {age}")
    case {"name": name}: // Match by name, age is optional
         print(f"User: {name} (age not specified)")
    case _:
        print("Invalid user data")

Example with a guard condition:

// Function with a guard condition
def process_number(n):
    match n:
        case int() if n > 0:
            // Matches only if n is an integer and greater than 0
            print(f"Positive integer: {n}")
        case int() if n < 0:
            // Matches only if n is an integer and less than 0
            print(f"Negative integer: {n}")
        case 0:
            // Matches zero
            print("Zero")
        case _:
            // Matches any other value
            print(f"Non-integer or zero: {n}")

// Using the function
process_number(5)
process_number(-3)
process_number(0)
process_number(3.14)

Advantages of match/case:

  • Readability: Improves code readability compared to long chains of if/elif/else, especially when matching different data types and structures.
  • Type safety: Allows checking data types in patterns.
  • Data extraction: Simplifies extracting data from complex structures (lists, tuples, dictionaries) directly during matching.
  • Expressiveness: Provides a more expressive way to handle multiple conditions based on data structure and value.

Differences from if/elif/else:

match/case is more specialized for matching form and structure of data, whereas if/elif/else is used for checking conditions based on values or expressions. match/case offers a more compact and semantically appropriate way for scenarios where different actions need to be performed depending on the type or structure of input data.

What are match/case constructs in Python? — Python - sobes.tech