3. Use structural pattern matching for structural dispatch
When branching on the shape of structured data, pattern matching can be clearer than a long if/elif chain.
Pattern matching becomes especially valuable when the condition depends on both the kind of input and the fields available on that input. It keeps the dispatch logic in one place and makes it easier to add new shapes without growing a fragile ladder of nested checks.
Note
Python 3.10+
3.1. Don’t do this
1event = {'type': 'click', 'x': 10, 'y': 20}
2
3if event.get('type') == 'click':
4 print(event['x'], event['y'])
5elif event.get('type') == 'keypress':
6 print(event['key'])
3.2. Do this
1event = {'type': 'click', 'x': 10, 'y': 20}
2
3match event:
4 case {'type': 'click', 'x': x, 'y': y}:
5 print(x, y)
6 case {'type': 'keypress', 'key': key}:
7 print(key)