Pattern matching
One of the most eye-catching features of Python 3.10 is the new match-casePattern matching. It is not just a "Python version of Switch", but a powerful tool that can deconstruct complex data, extract variables according to structure, and accurately match combinations of conditions. Originally I needed a bunch ofif-elifThe logic that can only be achieved by adding temporary variables can now be written as simple and intuitive as data description.
1. Basic entry: like Switch but more elegant
Let’s start with the most “Switch-like” usage, and you will immediately appreciate its simplicity.
1.1 Single value matching
Matching is performed sequentially from top to bottom, and the first one that matches successfullycaseThe branch will be executed, and subsequent ones will not be checked again._It must be placed last, otherwise subsequent branches will never be triggered.
1.2 Comparison of traditional writing methods
The same logic if usedif-elif-else, you need to write the same variable repeatedly:
match-caseThe advantage is clear goals and clear structure - you can see at a glance that all branches deal withscore, there will be no "a certainelifThe embarrassment of accidentally writing the wrong variable".
2. Advanced usage: Patterns are much more than constants
match-caseThe real power of "patterns" is that they can be nested, variables can be bound, and conditions can be added.
2.1 Multi-value combinations and guard conditions
use|Several constants can be combined into a pattern usingifAdd "guard" for further filtering:
Tips:
case x if x < 10inxMatching values will be captured, followed by guard conditionsif x < 10Then decide whether you really want to take this branch. This writing method is particularly suitable for the scenario of "match first and then verify the conditions".
2.2 Sequence deconstruction: lists and tuples in one move
When processing fixed-structure data such as command line parameters and coordinate lists, you can directly write the "structure" into the pattern:
here*filesJust like in function parameter unpacking*args, can collect all remaining elements in the list into a list.
3. advanced-features: dismantle complex objects
3.1 Match custom classes/data classes
Cooperatedataclass, you can directly match the object's attribute value pattern and automatically extract the required attributes into variables:
This way, we don't need to unpack the object first and then write a bunch ofif, the code reads like "if the point is at the origin, then so and so".
3.2 Partial matching of dictionary
Dictionary mode is equally powerful: you only need to match the keys you care about, and other keys will be ignored; if you want to retain unmatched key-value pairs, you can use**restcollect:
Notice:{'type': _}in_means "match any value, but do not bind variables", and the same as in the previous list_It's the same reason.
4. Pitfall avoidance guide and best practices
-
Matching order determines everything Pattern matching is performed strictly in the order in which the code is written. Once a hit is made, no further attempts will be made. So be sure to put the most specific and constrained mode first.
-
** wildcard
_Can only be placed at the end** if you putcase _:If it is written in the middle, all branches behind it will become "dead code", and there will be problems with the program logic. -
A beautiful way of writing type matching You can directly use the built-in type name as the pattern and bind the converted variable at the same time:
This is better thanisinstance()Adding temporary variables is much more refreshing.
- Simple branches do not need to be used deliberately
If there are only 2 to 3 single value judgments, directly use
if-elseMight be easier.match-caseThe advantage lies in complex structure matching rather than replacing allifstatement.
5. Two practical examples
5.1 HTTP status code processing
In back-end development or crawlers, it is often necessary to do different processing according to the status code. Usematch-caseYou can make the code clear at a glance:
The last branch is useless_Instead, it was usedcase code:, the effect is the same, and you can also access the specific value - this is a more friendly implementation.
5.2 Lightweight command line parser
Here is a simple interactive command loop that uses pattern matching for command parsing:
List mode coordination*and guard conditions, making command parsing safe and flexible, and especially convenient when adding new commands.
Summarize
Pythonmatch-caseFar from a simple Switch clone, it's a modern, expressive structured matchmaking system:
- ✅ Replace duplicates
if-elif-elsechain to make branch intentions clearer - ✅ Directly disassemble lists, tuples, dictionaries, and custom objects
- ✅ Combine guard conditions and variable binding to complete complex condition extraction
- ✅ Greatly improve code readability and maintainability
If you are using Python 3.10 and above, when encountering multi-branch + data extraction scenarios, please give priority tomatch-case, it will make your code concise and professional.

