(One of my summaries of a talk at a Dutch python meeting, this one organised by Ordina in october 2021 at the Amersfoort zoo)
Structural pattern matching (PEP (python enhancement proposal) 634) is the main new feature of the new python 3.10.
Not everyone was happy with structural pattern matching. One of the comments: I see the match statement as a domain specific language that looks like python, but that does something surprisingly differently. Yes it is a special mini-language. A bit like regular expressions, which is also a special mini-language within python.
What is structural pattern matching?
It is not a simple C++ “switch” statement. One of the differences is that python’s “match” statement only matches one of the patterns: with C++, you’d have to add “break” statements otherwise you can have multiple matches.
It is not just matching string literals.
Structural pattern matching tries to match objects by their shape. So: the value and/or the type. For sequences: how many elements? Dicts: which keys? What kind of values? Which attributes does an object have?
This is how it looks:
match <target>:
case <pattern> [if <guard>]:
<block of code>
case <pattern> [if <guard>]:
<block of code>
And an example:
match my_target:
case int():
print("I'm an int")
case str():
print("I'm a string")
The int()
looks a bit strange. You’re calling a type, at least that’s what
it looks like. But it is not. It is a bit misleading: it really looks like
python code, but it is not what you think it is. It is a custom way to express
your pattern. It is a nice short way to specify an isinstance()
check.
You can combine subpatterns with OR (|
). So case 200|400|404
.
Handy: sequence patterns:
case "MOVE", direction, distance:
move_player(direction, distance)
case "SELL", *items:
sell_items(items)
He showed a couple of nice examples. Looks like a useful new python feature!
My name is Reinout van Rees and I program in Python, I live in the Netherlands, I cycle recumbent bikes and I have a model railway.
Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):