4.1. Match About
Since Python 3.10: PEP 636 -- Structural Pattern Matching: Tutorial
Significantly faster for sequences and mappings [1]
Since Python 3.11: For sequences if faster around 80% [1]
Since Python 3.11: For mappings if faster around 80% [1]
https://github.com/python/cpython/blob/main/Grammar/python.gram#L479
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
matchesMatch sequences using list or tuple syntax (like Python's existing
iterable unpacking
feature)Match mappings using
dict
syntaxUse
*
to match the rest of a listUse
**
to match other keys in a dictMatch 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'
- testsubject == 'x'
capture pattern:
x
- assignx = subject
x.y
- testsubject == x.y
x()
- testisinstance(subject, x)
{'x': 'y'}
- testisinstance(subject, Mapping) and subject.get('x') == 'y'
['x']
- testisinstance(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