Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to deeply understand Match Case in the latest Python

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

How to deeply understand the latest Python Match Case, I believe that many inexperienced people are helpless about this, for this reason this article summarizes the causes and solutions of the problem, through this article I hope you can solve this problem.

Some people still think Python doesn't need "switch-case" syntax. Even Guido himself doesn't support adding this syntax to Python. But why is it still released in this new version? In my opinion, the reason can be found in the name, which is called "match case" rather than "switch case" like most programming languages.

I'll use seven examples to demonstrate the flexibility and "pythonic" of the new syntax.

1. basis

Before anything fancy, let's start with the basic use cases of this new syntax. Assuming we are writing some code to convert HTTP status codes into error messages, we can use match-case syntax as follows:

In fact, for this particular example, match-case doesn't offer any advantage over if-else syntax, as shown below.

def http_error(status): if status == 400: return "Bad request" elif status == 401: return "Unauthorized" elif status == 403: return "Forbidden" elif status == 404: return "Not found" else: return "Unknown status code"

If it could only do something like that, I don't think it would be added. Let's continue with more examples to see how flexible it can be.

2. default

It means something similar to switch-case syntax in most other languages, so it must have a "default case." When no defined case matches, the code in "default case" is executed.

Python does this in style. It uses the underscore "_" for anonymous variables. The basic principle is that anonymous variables can "match" anything.

Let's look at the following example.

In the code above, we added the default and displayed "other errors."

3. merger cases

What if sometimes we have multiple cases that need to be merged? In other words, these are different situations, but the way we handle them should be the same.

In Python, we can use pipes.|"Combine these cases into one case. It is also considered an "or" relationship.

In the code above, we treat both 401 and 403 errors as authentication problems, so we can combine them into matching cases.

4. Wildcards in lists

Here comes something even more interesting. Suppose we are writing alarm logic using match-case syntax. It accepts a list as an argument. The first element is time. For example, there are "morning,""afternoon," and "evening." The second element is the action we need to do.

However, we may want alerts to remind us to do many things at once. Therefore, we want to pass multiple actions in the list so that alerts remind us to perform all actions one by one.

Here is the code to fulfill this requirement.

In this example, we have only two situations. The first case doesn't need much explanation because it's just trying to match a single action case. In the second case, we put an asterisk in front of the variable "actions" so that it matches one or more actions in the list!

5. submode

Sometimes we may want to include patterns in patterns. Specifically, we want matching cases to classify streams as specific "cases." However, in this pattern, we want to add more restrictions.

Remember we defined the "time" of day as "morning,""afternoon," or "evening"? Let's add this restriction to the matching case code. If Time does not match one of these three items, tell the user that the time is invalid.

In the code above, it shows that we can enclose the "patterns" we want to match with a pair of brackets and separate them with pipes.

If it doesn't match one of the given 3 "times," the default is enforced.

Why is there a question mark there? I intentionally added it because I wanted to emphasize the solution. In general, it is not easy to match one of the sub-patterns and then refer to the pattern that exactly matches it. However, we can have this "reference" in Python.

Let's add an "as" keyword, followed by a variable that will act as a reference.

6. conditional pattern

We need to make this alert smarter. At night, let's display some messages thanking users for completing their day's work. So we added another case to the code above to match only "evening."

Let's make this alert smarter to encourage users to "work life balance." Therefore, when the user wants to work or study at night, the alarm clock will suggest that the user take a break.

7. matching object

We've explored a lot so far, and I guess you might have the feeling that it's "match-case" rather than "switch-case," because "pattern" is always the key.

Let's have a more complicated example. Yes, let's match an object using match-case.

Let me make up a simple example. A class called Direction was created to maintain orientation on both horizontal (east or west) and vertical (north or south) axes.

class Direction: def __init__(self, horizontal=None, vertical=None): self.horizontal = horizontal self.vertical = vertical

Now we're going to use match-case syntax to match instances from this class and display a message based on attributes.

def direction(loc): match loc: case Direction(horizontal='east', vertical='north'): print('You towards northeast') case Direction(horizontal='east', vertical='south'): print('You towards southeast') case Direction(horizontal='west', vertical='north'): print('You towards northwest') case Direction(horizontal='west', vertical='south'): print('You towards southwest') case Direction(horizontal=None): print(f'You towards {loc.vertical}') case Direction(vertical=None): print(f'You towards {loc.horizontal}') case _: print('Invalid Direction')

Then, let's create some objects from the class for testing.

d1 = Direction('east', 'south')d2 = Direction(vertical='north')d3 = Direction('centre', 'centre')

The results show that match-case can easily match these objects based on their attributes!

I introduced the new syntax "match-case" introduced in Python 3.10 and how flexible and powerful it is. I believe mastering this new syntax will help us write better code in terms of readability.

After reading the above, do you know how to understand the Match Case method in the latest Python? If you still want to learn more skills or want to know more related content, welcome to pay attention to the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report