I couldn't find any information on whether this was considered and rejected during the pattern matching PEP, so apologies if this is already settled.
I've just encountered this use-case repeatedly so I figured it was time to make a thread on this.
Basically, I'd like to be able to designate a pattern like this:
match val:
case [*str()]:
...
Where 'val' will match an iterable containing zero or more strings.
This should also work with more complex sub-patterns, like:
match humans:
case [
*{
'name': str(),
'age': int(),
}
]:
...
Where 'humans' should match an iterable of zero or more mappings where each
mapping
contains the keys 'name' and 'age' (and where the value for name is a string and the value for age is an int).
Sure, you can use the sentinel clause to do it, but imagine you've got a case statement where you're using 10 different variadic sub-patterns. You'd have an unbearably long string of:
case {PATTERN_GOES_HERE} if (
all(isinstance(val1, some_type1) for val1 in sub_pattern1)
and all(isinstance(val2, some_type2) for val2 in sub_pattern2)
and ...
)
And that's assuming simple variadics like my first example above, and not my second example!
This incidentally destroys the gain in legibility of using a pattern in the first place.
Is anyone aware of a reason variadic patterns weren't included in the PEP? Was it an oversight, or was it deemed too niche to include in the
original spec? Or were there implementation-related reasons? Something
else?
It just seems like it would make
match statements way more powerful for data shape validation, which is
one of the primary use-cases that the tutorial PEP showed off.
Cheers