Categories: Python
Tags:

The match statement in Python, introduced in Python 3.10, is a structural pattern matching feature that allows developers to check a value against a series of patterns, executing code based on the first match. It is similar to switch-case statements found in other languages like C or JavaScript but is far more powerful and versatile.


Syntax of match

match subject:
    case pattern1:
        # Code block if pattern1 matches
    case pattern2:
        # Code block if pattern2 matches
    case _:
        # Code block if no pattern matches (default case)
  • subject: The value to be matched.
  • case: Represents a specific pattern to match against the subject.
  • _: Acts as a wildcard to match anything (like a “default” case).

Basic Example

command = "start"

match command:
    case "start":
        print("Starting...")
    case "stop":
        print("Stopping...")
    case _:
        print("Unknown command")

Output:

Starting...

Powerful Features of match

1. Matching Literal Values

x = 10

match x:
    case 0:
        print("Zero")
    case 10:
        print("Ten")
    case _:
        print("Other number")

2. Matching Data Structures

You can match lists, tuples, or dictionaries.

data = ("hello", 42)

match data:
    case ("hello", 42):
        print("Exact match!")
    case (str_value, int_value):
        print(f"String: {str_value}, Integer: {int_value}")

3. Matching Classes

You can match attributes of objects, such as data classes.

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

p = Point(1, 2)

match p:
    case Point(x=1, y=2):
        print("Point at (1, 2)")
    case Point(x=1, y=y_val):
        print(f"Point with x=1 and y={y_val}")

4. Wildcard and Guards

  • _ is a wildcard that matches anything.
  • Guards (if) add conditional checks to patterns.
x = 10

match x:
    case _ if x > 5:
        print("Greater than 5")
    case _:
        print("Five or less")

5. Nested Patterns

data = {"key": {"subkey": 10}}

match data:
    case {"key": {"subkey": value}}:
        print(f"Value is {value}")

Use Cases

  1. Parsing command-line arguments.
  2. Handling multiple cases for input data.
  3. Simplifying nested if-elif chains.
  4. Deconstructing complex data structures like dictionaries, tuples, or custom classes.

Advantages

  1. More expressive than traditional if-elif chains.
  2. Provides pattern matching capabilities similar to functional languages like Haskell or Scala.
  3. Makes the code more readable and concise, especially when handling complex conditions.

This addition greatly enhances Python’s capabilities for working with structured data and conditional logic.