In Python 3.10, a structural pattern matching mechanism was introduced (structural pattern matching), using the match-case statement. Historically, in Python, complex conditions have been implemented using if/elif/else chains, which were inconvenient when analyzing nested structures (for example, dictionaries, nested tuples).
Problem — complex nested checks become hard to read and maintain. The match-case approach allows concise descriptions of checks with variable unpacking and guard conditions.
Solution — use the match-case syntax, which matches the structure of an object (dictionaries, tuples, lists) with a specified pattern and extracts data.
Example code:
point = (1, 2) match point: case (0, 0): print('Origin') case (0, y): print(f'Y={y}') case (x, 0): print(f'X={x}') case (x, y): print(f'X={x}, Y={y}')
Key features:
Can match-case be used for regular if-elif-else conditions on individual values?
Yes, however, the strength of match-case lies in its structural matching. For simple discrete conditions, it is similar to the switch-case statements of languages like C.
Can match-case be used with immutable objects (e.g., str)?
Yes, match-case works with any objects that can be compared to a pattern, including strings and numbers.
Example code:
color = 'red' match color: case 'red': print('This is red') case 'blue': print('This is blue') case _: print('Unknown color')
What error occurs when matching objects with the same variable names in the outer scope?
Pattern matching assigns variables locally within the case, regardless of the outer context. This can lead to confusion if the variable name is already used outside.
Using match-case for a large if-elif-else statement with simple constants.
Pros:
Cons:
Processing a stream of nested JSON structures from an API, where different cases require different data extraction from various levels of the structure.
Pros:
Cons: