ProgrammingPython Developer

Explain the pattern matching mechanism in Python 3.10+: how to use it, how it differs from if/elif/else chains, and what nuances to consider?

Pass interviews with Hintsage AI assistant

Answer.

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:

  • The ability to match the structure of objects, not just values.
  • Support for guard conditions (if-after-case).
  • Automatic unpacking of variables.

Trick questions.

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.

Common errors and anti-patterns

  • Using match-case for simple discrete conditions (comparing numbers/strings) when if/elif is sufficient.
  • Errors in unpacking: confusing the pattern structure and the actual object (ValueError upon mismatch).
  • Issues with the scope of variables assigned within case statements.

Real-life example

Negative case

Using match-case for a large if-elif-else statement with simple constants.

Pros:

  • More concise than a long chain of if-elif.

Cons:

  • No advantages over classic if/elif.
  • Potentially complicates understanding for colleagues unfamiliar with the new syntax.

Positive case

Processing a stream of nested JSON structures from an API, where different cases require different data extraction from various levels of the structure.

Pros:

  • The code reads like a description of the data structure.
  • Reduces errors in unpacking.

Cons:

  • Requires the whole team to learn the match-case syntax.
  • Does not work in Python versions below 3.10.