4.1. Match About

4.1.1. Problem

>>> color = 'r'
>>>
>>> if color == 'r':
...     print('red')
... elif color == 'g':
...     print('green')
... elif color == 'b':
...     print('blue')
...
red

4.1.2. Solution

>>> color = 'r'
>>>
>>> match color:
...     case 'r': print('red')
...     case 'g': print('green')
...     case 'b': print('blue')
...
red

4.1.3. 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

Pattern matching is a shortcut for:

  • literal pattern: 'x' - test subject == 'x'

  • capture pattern: x - assign x = subject

  • 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]

4.1.4. Use Case - 1

Problem:

>>> 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

Solution:

>>> 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

4.1.5. Further Reading

4.1.6. References