Match Statement in Python

Overview

The match statement in Python, introduced in version 3.11, is a powerful feature for structural pattern matching. It allows developers to select between multiple options based on matching values or types, providing a more sophisticated alternative to traditional switch or case statements found in other programming languages. The match statement is structured with case statements to define patterns and includes an optional default case using _.

Structure of match: case Statement

The basic structure of a match: case statement is as follows:

match expression: 
    case test_expression:
       code block for match
    case _:
       code block if no match (optional)
  • Expression: Typically a variable or object that you want to match against.
  • Test Expression: Can be a specific value, object, type function, or class constructor. It is also possible to match multiple options using the "or" operator |.
  • Default Case: The underscore _ can be used as a default case, which will be executed if none of the other cases match. If no cases match and no default is provided, no code is executed.

Example Usage

Consider the following example, which demonstrates the use of the match statement to check for various conditions:

x = 5
match x:
  case "A":  #A
    print("A")
  case str():   #B
    print("some other string")
  case 0:   #C
    print("Zero")
  case 1 | 2 | 3:   #D
    print(f"value {x} in range")
  case int():    #E
    print(f"The integer {x}")
  case _:    #F
    print("Neither string nor int")
#A Matches exactly “A”.
#B Matches any other string.
#C Matches exactly 0.
#D Matches any of 1, 2, or 3.
#E Matches any other int.
#F Executed if no match (optional). 

In this example:

  • The code checks if x matches the string "A", any other string, the integer 0, any of the integers 1, 2, or 3, or any other integer.
  • If none of these conditions are met, the default case (_) is executed, printing "Neither string nor int".

Considerations

While pattern matching is a powerful tool, it can also introduce complexity. The various ways expressions can be matched may lead to unexpected behavior. It is advisable to thoroughly read the documentation and consider potential edge cases when using match in your code. The Python tutorial online at https://docs.python.org is a recommended resource for further reading.

FAQ (Frequently asked questions)

What is the 'match' statement in Python used for?

When was the 'match' statement introduced in Python?

Is the 'match' statement in Python more powerful than traditional 'switch' or 'case' statements in other languages?