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
4.1.1. Problem¶
>>> choice = 'r'
>>>
>>> if choice == 'r':
... color = 'red'
... elif choice == 'g':
... color = 'green'
... elif choice == 'b':
... color = 'blue'
... else:
... color = None
4.1.2. Pattern Matching¶
New match
syntax allows to be PEP-8
compliant while having
clear syntax without condition repetitions:
>>> choice = 'r'
>>>
>>> match choice:
... case 'r': color = 'red'
... case 'g': color = 'green'
... case 'b': color = 'blue'
... case _: color = None
4.1.3. Syntax¶
>>>
... match <object>:
... case <option>: <action>
... case <option>: <action>
... case <option>: <action>
... case _: <default action>
4.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
4.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
4.1.6. Further Reading¶
4.1.7. References¶
- 1(1,2,3)
Anthony Shaw. Write faster Python! Common performance anti patterns. Year: 2022. Retrieved: 2022-06-09. URL: https://youtu.be/YY7yJHo0M5I?t=1555
- 2
Raymond Hettinger. Year: 2021. Retrieved: 2021-03-07. URL: https://twitter.com/raymondh/status/1361780586570948609?s=20