3.1. Match About

3.1.1. Problem

It all starts with single if/else statement

>>> language = 'English'
>>>
>>> if language == 'English':
...     result = 'Hello'
... else:
...     result = 'Unknown language'
>>>
>>> print(result)
Hello

It quickly grows:

>>> language = 'English'
>>>
>>> if language == 'English':
...     result = 'Hello'
... elif language == 'Polish':
...     result = 'Cześć'
... else:
...     result = 'Unknown language'
>>>
>>> print(result)
Hello

It quickly grows into multiple elif:

>>> language = 'English'
>>>
>>> if language == 'English':
...     result = 'Hello'
... elif language == 'Polish':
...     result = 'Cześć'
... elif language == 'German':
...     result = 'Guten Tag'
... elif language == 'Spanish':
...     result = 'Buenos Días'
... elif language == 'Chinese':
...     result = '你好'
... elif language == 'French':
...     result = 'Bonjour'
... else:
...     result = 'Unknown language'
>>>
>>> print(result)
Hello

3.1.2. Pattern Matching

New match syntax allows to be PEP-8 compliant while having clear syntax without condition repetitions:

>>> language = 'English'
>>>
>>> match language:
...     case 'English': result = 'Hello'
...     case 'Polish':  result = 'Cześć'
...     case 'German':  result = 'Guten Tag'
...     case 'Spanish': result = 'Buenos Días'
...     case 'Chinese': result = '你好'
...     case 'French':  result = 'Bonjour'
...     case _:         result = 'Unknown language'
>>>
>>> print(result)
Hello

3.1.3. Syntax

>>> 
... match <object>:
...     case <option>: <action>
...     case <option>: <action>
...     case <option>: <action>
...     case _: <default action>

3.1.4. Patterns

  • literal pattern

  • capture pattern

  • wildcard pattern

  • constant value pattern

  • sequence pattern

  • mapping pattern

  • class pattern

  • OR pattern

  • walrus pattern

Patterns don't just have to be literals. The patterns can also:

  • Use variable names that are set if a case matches

  • Match sequences using list or tuple syntax (like Python's existing iterable unpacking feature)

  • Match mappings using dict syntax

  • Use * to match the rest of a list

  • Use ** to match other keys in a dict

  • Match objects and their attributes using class syntax

  • Include "or" patterns with |

  • Capture sub-patterns with as

  • Include an if "guard" clause

3.1.5. Recap

  • x - assign x = subject

  • 'x' - test subject == 'x'

  • x.y - test subject == x.y

  • x() - test isinstance(subject, x)

  • {'x': 'y'} - test isinstance(subject, Mapping) and subject.get('x') == 'y'

  • ['x'] - test isinstance(subject, Sequence) and len(subject) == 1 and subject[0] == 'x'

  • Source: [2]

3.1.6. Further Reading

3.1.7. References