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?
>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")