|
|
Python match Statement
Author: Venkata Sudhakar
The match statement was introduced in Python 3.10 as structural pattern matching. It looks similar to a switch statement from other languages, but it is much more powerful - it can match against values, types, shapes of data structures, and even unpack variables from the matched object in one step. It is especially useful when handling different types of commands, events, or API responses where each shape requires different handling. The basic syntax is match subject: followed by case pattern: blocks. Python tries each case from top to bottom and runs the first one that matches. A lone underscore _ is the wildcard that matches anything and acts as the default case. The below example shows matching against values, types, and structured data - a common pattern when routing commands in a CLI tool or handling CDC event types.
It gives the following output,
INSERT
UPDATE
Unknown operation: x
It gives the following output,
Migrating table: customers
Validating 5000 rows in orders
Rolling back last migration
Unknown action: purge
The key advantage over if/elif chains is that match unpacks the data and binds variables at the same time - case {"action": "migrate", "table": table} both checks that "action" equals "migrate" AND extracts the "table" value into the variable table in one step. This makes code handling complex data structures much cleaner and easier to read.
|
|