Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Structural pattern matching for list of unknown length in Python 3.10

Let’s assume I have the following function:

def sum_ints(my_list: list[int]) -> int:
    return sum(my_list)

Before I start adding the elements in my_list, I want to check the type of all elements using the new match statement.

If my_list has a length of 2 for example, I can do:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def sum_ints(my_list: list[int]) -> int:
    match my_list:
        case [int(), int()]:
            return sum(my_list)
        case _:
            raise Exception("...")

How can I match the case for a list with n elements?

>Solution :

I think in your case you only need all built-in function.

if all(isinstance(i, int) for i in my_list):
    # Do Something
else:
    # raise Exception("...")

But if you really really want to try this logic via match statement you can use match guard but it’s kind of a complicated/unreadable solution in this case.

a = [1, 2]
match a:
    case [*elements] if all(isinstance(i, int) for i in elements):
        print("All Int")
    case _:
        raise Exception("test")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading