Plain English Westminster
benhoyt.com › writings › python-pattern-matching
Structural pattern matching in Python 3.10
A critical but informative look at the new structural pattern matching feature in Python 3.10, with real-world code examples.
8 Levels of Using Structure Pattern Matching in Python
Nice article! It would help to have side-by-side comparisons of how you would accomplish the same tasks with if/else statements instead, to better illustrate the clarity and efficiency of the match statement. For example, this one's not so different: def handle_http_status(status_code): if status_code == 200: return "Success!" elif status_code in (400, 401, 403, 404): return f"Client Error:{status_code}" elif status_code in (500, 501, 502, 503, 504): return f"Server Error:{status_code}" else: return "Unknown Status" The "as err" option doesn't do much in the examples given, since you already have that value in status_code. So I simply reference status_code in the return lines. The shape example could be expressed with if/else like so: def process_shape(shape): if isinstance(shape, Circle): return f"Processing a circle with radius {shape.radius}" elif isinstance(shape, Rectangle): return f"Processing a rectangle with length {shape.length} and width {shape.width}" if isinstance(shape, Triangle): return f"Processing a triangle with base {shape.base} and height {shape.height}" else: return "Unknown shape" This is certainly more verbose than the match statement. Again, I have simply shifted the variable capture into the return statement, because why not? So far, so good. But wait! Let's try that dict example. def handle_user_action(action): if all(k in action for k in ('type', 'username', 'password')) and action['type']=='login': return f"Login attempt by {action['username']} with password {action['password']}" elif all(k in action for k in ('type', 'username')) and action['type']=='logout': return f"User {action['username']} logged out" elif all(k in action for k in ('type', 'username', 'email')) and action['type']=='signup': return f"New signup by {action['username']} with email {action['email']}" else: return "Unknown action" YUCK! Painful to read, and painful to write. You end up using the literal keys multiple times, leaving more potential for typos and sneaky bugs. You need to check each key's existence separately from checking its value. What a mess. I kept this example as simple as I could while maintaining a perfectly equivalent logical flow to the match example in the article, and keeping each if condition independent from others. In reality, if I had to use if/elif/else for this, I would use a fundamentally different structure, because this one sucks. I would probably split this into multiple if blocks, and capture the values into variables as early as possible to avoid using literal keys multiple times. This would add additional complexity. For example, I could check for the existence of the 'type' and 'username' keys first, before even starting this if statement, since every single case we use checks for them. But then what happens if I need to add more complex cases later that don't have all those same requirements? Better to keep each case independent -- or at least, it's better with the match statement, because it's designed to make that easy, efficient, safe, and readable. It's difficult to express the utility of the match statement with simple examples, because if/else is perfectly fine for those (always has been!). The simple examples don't really justify the complexity of adding a whole new type of statement block, but for advanced use cases, the advantage of match over if/elif/else widens significantly. There are even more complex and powerful things you can do with match. See https://peps.python.org/pep-0636/ for more details. More on reddit.com
How to use Python pattern matching to match class types? - Stack Overflow
How can we use Python's structural pattern matching (introduced in 3.10) to match the type of a variable without invoking the constructor / in a case where a new instantiation of the class is not e... More on stackoverflow.com
Stack Overflow Users Rejoice as Pattern Matching is Added to Python 3.10
How many pythons does it take to operate a switch? More on reddit.com
You can use 3.10's new structural pattern matching feature to easily flatten deeply nested lists, tuples and sets.
I programmatically solved this in python 3.8, I'm excited to see how 3.10 simplifies this. Thanks for the post More on reddit.com
Videos
04:51
Master Pattern Matching In 5 Minutes | All Options | Python 3.10 ...
35:56
Understanding Python: Structural Pattern Matching - YouTube
18:25
Using Structural Pattern Matching in Python: Using Basic Patterns ...
09:59
Python Structural Pattern Matching - Intro with Examples - YouTube
12:33
Structural Pattern Matching in Python: Not Your Average Switch-Case ...
Martin Heinz
martinheinz.dev › blog › 78
Recipes and Tricks for Effective Structural Pattern Matching in Python | Martin Heinz | Personal Website & Blog
August 2, 2022 - Common use case for match/case is efficient matching of JSON structures in form of Python's dictionaries. This can be done with mapping pattern which is triggered by case {...}: ...
Python
peps.python.org › pep-0636
PEP 636 – Structural Pattern Matching: Tutorial | peps.python.org
If the pattern matches but the condition is falsy, the match statement proceeds to check the next case as if the pattern hadn’t matched (with the possible side-effect of having already bound some variables). Your adventure is becoming a success and you have been asked to implement a graphical interface. Your UI toolkit of choice allows you to write an event loop where you can get a new event object by calling event.get(). The resulting object can have different type and attributes according to the user action, for example:
ArjanCodes
arjancodes.com › blog › how-to-use-structural-pattern-matching-in-python
Introduction to Structural Pattern Matching in Python | ArjanCodes
June 20, 2024 - Structural pattern matching is a feature that allows you to check a value against a pattern, extracting parts of the value if the pattern matches. This can make complex conditionals simpler and more readable. ... def http_status(status: int) -> str: match status: case 200: return "OK" case 404: return "Not Found" case 500: return "Internal Server Error" case _: return "Unknown Error" In the example above, match is a keyword introduced in Python 3.10, which, combined with case, allows for clean and readable pattern matching.
InfoWorld
infoworld.com › home › software development › programming languages › python
How to use structural pattern matching in Python | InfoWorld
August 9, 2023 - That said, enums tend to be the most familiar and idiomatic way to do this in Python. You cannot match against variable contents through indexing. For instance, case commands[0]: would be rejected as a syntax error. The key to working most effectively with pattern matching is not just to use it as a substitute for a dictionary lookup or an if/else chain.
Real Python
realpython.com › structural-pattern-matching
Structural Pattern Matching in Python – Real Python
August 6, 2024 - Python supports several types of structural patterns, which you’ll explore in detail throughout this tutorial. Each pattern describes the structure of an object to match, including its type, shape, value, and identity. It can also specify the individual pieces of which an object is made. For example, you may want to define a pattern that will match three-dimensional points that lie on the z-axis:
Python Engineer
python-engineer.com › posts › pattern-matching-python
Master Pattern Matching In Python 3.10 | All Options | - Python Engineer
For example the value 400 here prints only Bad request. In other languages like C++ this would then fall through all cases and also print all other statements, unless we use a break statement. But we don’t need this here in Python. def http_error(status): match status: case 400: print("Bad request") case 401 | 403 | 404: print("Not allowed") A single underscore is used as the wildcard. This means if none of the above patterns matches, the wildcard action is performed.
Python
peps.python.org › pep-0634
PEP 634 – Structural Pattern Matching: Specification | peps.python.org
An OR pattern matches each of its subpatterns in turn to the subject, until one succeeds. The OR pattern is then deemed to succeed. If none of the subpatterns succeed the OR pattern fails. ... literal_pattern: | signed_number | signed_number '+' NUMBER | signed_number '-' NUMBER | strings | 'None' | 'True' | 'False' signed_number: NUMBER | '-' NUMBER · The rule strings and the token NUMBER are defined in the standard Python grammar.
Medium
medium.com › data-engineering-with-dremio › leveraging-pythons-pattern-matching-and-comprehensions-for-data-analytics-9293a7921db5
Leveraging Python’s Pattern Matching and Comprehensions for Data Analytics | by Alex Merced | Data, Analytics & AI with Dremio | Medium
November 7, 2024 - We’ll dive into practical examples of how pattern matching and comprehensions can be applied to streamline data processing, showing how they simplify complex tasks and optimize data workflows. By the end, you’ll have a clearer understanding of how these Python features can enhance your ...
Reddit
reddit.com › r/python › 8 levels of using structure pattern matching in python
r/Python on Reddit: 8 Levels of Using Structure Pattern Matching in Python
December 24, 2023 -
There is one feature that Python developers waiting for so long: structural pattern matching. It finally became possible since Python 3.10. This article will show you all tricks of it in 8 levels of difficulty.
Top answer 1 of 4
31
Nice article! It would help to have side-by-side comparisons of how you would accomplish the same tasks with if/else statements instead, to better illustrate the clarity and efficiency of the match statement. For example, this one's not so different: def handle_http_status(status_code): if status_code == 200: return "Success!" elif status_code in (400, 401, 403, 404): return f"Client Error:{status_code}" elif status_code in (500, 501, 502, 503, 504): return f"Server Error:{status_code}" else: return "Unknown Status" The "as err" option doesn't do much in the examples given, since you already have that value in status_code. So I simply reference status_code in the return lines. The shape example could be expressed with if/else like so: def process_shape(shape): if isinstance(shape, Circle): return f"Processing a circle with radius {shape.radius}" elif isinstance(shape, Rectangle): return f"Processing a rectangle with length {shape.length} and width {shape.width}" if isinstance(shape, Triangle): return f"Processing a triangle with base {shape.base} and height {shape.height}" else: return "Unknown shape" This is certainly more verbose than the match statement. Again, I have simply shifted the variable capture into the return statement, because why not? So far, so good. But wait! Let's try that dict example. def handle_user_action(action): if all(k in action for k in ('type', 'username', 'password')) and action['type']=='login': return f"Login attempt by {action['username']} with password {action['password']}" elif all(k in action for k in ('type', 'username')) and action['type']=='logout': return f"User {action['username']} logged out" elif all(k in action for k in ('type', 'username', 'email')) and action['type']=='signup': return f"New signup by {action['username']} with email {action['email']}" else: return "Unknown action" YUCK! Painful to read, and painful to write. You end up using the literal keys multiple times, leaving more potential for typos and sneaky bugs. You need to check each key's existence separately from checking its value. What a mess. I kept this example as simple as I could while maintaining a perfectly equivalent logical flow to the match example in the article, and keeping each if condition independent from others. In reality, if I had to use if/elif/else for this, I would use a fundamentally different structure, because this one sucks. I would probably split this into multiple if blocks, and capture the values into variables as early as possible to avoid using literal keys multiple times. This would add additional complexity. For example, I could check for the existence of the 'type' and 'username' keys first, before even starting this if statement, since every single case we use checks for them. But then what happens if I need to add more complex cases later that don't have all those same requirements? Better to keep each case independent -- or at least, it's better with the match statement, because it's designed to make that easy, efficient, safe, and readable. It's difficult to express the utility of the match statement with simple examples, because if/else is perfectly fine for those (always has been!). The simple examples don't really justify the complexity of adding a whole new type of statement block, but for advanced use cases, the advantage of match over if/elif/else widens significantly. There are even more complex and powerful things you can do with match. See https://peps.python.org/pep-0636/ for more details.
2 of 4
7
Nice summary. Especially the last couple entries-- matching against a dictionary and matching against a class declaratio, I would never have thought to try. And they’re really useful!
Medium
medium.easyread.co › enhance-your-python-skills-leveraging-pattern-matching-with-match-96382177869e
Enhance Your Python Skills: Leveraging Pattern Matching with “match” | by Ferdina Kusumah | Easyread
July 16, 2024 - Here’s an example of literal patterns: case 0: # code for when the expression is 0 case "hello": # code for when the expression is the string "hello" case 1.5: # code for when the expression is float 1.5 case True: # code for when the expression is boolean true · Variable binding patterns in Python’s match statement allow you to not only match a value against a pattern but also bind that value to a variable for use within the corresponding code block.
Python documentation
docs.python.org › 3 › library › re.html
re — Regular expression operations
4 days ago - Will try to match with yes-pattern if the group with given id or name exists, and with no-pattern if it doesn’t. no-pattern is optional and can be omitted. For example, (<)?(\w+@\w+(?:\.\w+)+)(?(1)>|$) is a poor email matching pattern, which will match with '<user@host.com>' as well as 'user@host.com', but not with '<user@host.com' nor 'user@host.com>'.
W3Schools
w3schools.com › python › python_regex.asp
Python RegEx
Python has a built-in package called re, which can be used to work with Regular Expressions. ... You can add flags to the pattern when using regular expressions. A special sequence is a \ followed by one of the characters in the list below, and has a special meaning: A set is a set of characters inside a pair of square brackets [] with a special meaning: The findall() function returns a list containing all matches...
Python
peps.python.org › pep-0622
PEP 622 – Structural Pattern Matching | peps.python.org
During this matching process, the structure of the pattern may not fit the subject, and matching fails. For example, matching the pattern Point2d(x, 0) to the subject Point2d(3, 0) successfully matches.
W3Schools
w3schools.com › python › python_match.asp
Python Match
If there is a match, the associated block of code is executed. The example below uses the weekday number to print the weekday name: