Structural Pattern Matching in Python — ELI5
Picture a mail sorting machine at the post office. Letters come in different shapes — small envelopes, big parcels, tubes with posters inside. The machine doesn’t open them. It looks at the shape and sends each piece to the right bin.
Structural pattern matching in Python works the same way. You give it a value, and Python checks its shape — is it a list with two items? A dictionary with a “type” key? A number bigger than zero? — and runs the matching code.
Before this feature existed (it arrived in Python 3.10), programmers wrote long chains of if/elif/else statements. It worked, but it looked messy, especially when checking complicated nested data.
With match, you write each possible shape as a case. Python goes through the cases top to bottom, finds the first one that fits, and runs that block. If nothing matches, it moves on — no crash, no error.
The cool part is unpacking. When the shape matches, Python can pull out the pieces for you. If the value is a list with exactly two numbers, the match grabs both numbers and gives them names you can use inside the block. It’s like the sorting machine not only recognising a parcel but also reading the address label for you.
This makes code easier to read because the shape of the data and the code that handles it sit right next to each other.
The one thing to remember: Structural pattern matching lets Python look at the shape of data and run the right code automatically — like a smart sorting machine for your variables.
See Also
- Python 310 New Features Python 3.10 gave programmers a shape-sorting machine, friendlier error messages, and cleaner ways to say 'this or that' in type hints.
- Python 311 New Features Python 3.11 made everything faster, error messages smarter, and let you catch several mistakes at once instead of stopping at the first one.
- Python 312 New Features Python 3.12 made type hints shorter, f-strings more powerful, and started preparing Python's engine for a world without the GIL.
- Python 313 New Features Python 3.13 finally lets multiple tasks run at the same time for real, added a speed booster engine, and gave the interactive prompt a colourful makeover.
- Python Exception Groups Python's ExceptionGroup is like getting one report card that lists every mistake at once instead of stopping at the first one.