Question:
How to use Python pattern matching to match class types?

Summary: 

In Python, you can use pattern matching (also known as structural pattern matching or match statement) introduced in Python 3.10 to match class types. Pattern matching allows you to write more concise and readable code for conditional branching based on the structure of data. 


Solution:

You can use the below code to match class type in Python

class Tree:

    def __init__(self, name):

        self.kind = name

    

def what_is(t):

    match t:

        case Tree(kind="oak"):

            return "oak"

        case Tree():

            return "tree"

        case _:

            return "shrug"


print(what_is(Tree(name="oak")))    # oak

print(what_is(Tree(name="birch")))  # tree

print(what_is(17))                  # shrug


TypeError: Tree.__init__() got an unexpected keyword argument 'kind'


match Tree:

    case type(__init__=initializer):

        print("Tree is a type, and this is its initializer:")

        print(initializer)


# => Tree is a type, and this is its initializer:

#    <function Tree.__init__ at 0x1098593a0>


Explanation:

Here's what each case does:


  • case Tree(kind="oak"):: Matches instances of Tree with kind attribute set to "oak".

  • case Tree():: Matches any instance of Tree regardless of its kind attribute.

  • case _:: Matches any other input that doesn't match the above cases.


Answered by: >Amadan

Credit: >Stackoverflow


Suggested blogs:

>How .transform handle the splitted groups?

>Can I use VS Code's launch config to run a specific python file?

>Python: How to implement plain text to HTML converter?

>How to write specific dictionary list for each cycle of loop?

>Reading a shapefile from Azure Blob Storage and Azure Databricks

>How to replace a value by another in certain columns of a 3d Numpy array?

>How to fix "segmentation fault" issue when using PyOpenGL on Mac?


Submit
0 Answers

What Our Clients Say About Us

Client satisfaction is our ultimate goal. Here are some kind words of our precious clients they have used to express their satisfaction with our service.

Why Choose Us ?

We endow businesses with flexible engagement models based on their unique needs. Our strength lies in state-of-the-art technology and affordable consulting services. Try us for fast POCs, full-fledged applications, or technology consulting. Always available for your service.