1

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:

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?

Deneb
  • 981
  • 2
  • 9
  • 25
  • 2
    Did you mean `if all(isinstance(i, int) for i in my_list)`? Why do you need a match statement? – Abdul Niyas P M Jan 14 '22 at 13:22
  • 1
    @AbdulNiyasPM This example was for the sake of simplicity as to understand if there's a `match` equivalent to achieve this. If I wanted to know an alternative, I would've reformulated my question. – Deneb Jan 14 '22 at 13:35

1 Answers1

4

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 have to capture the elements first and use match guard to verify the condition, 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 elements are int")
    case _:
        raise Exception("Elements are not int")

See Also:

Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46