3.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
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
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
3.1.5. Recap
x
- assignx = subject
'x'
- testsubject == 'x'
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]