Description
When multiple case patterns execute similar block of code in a match
statement (structural pattern matching), this can be boiled down to avoid duplication.
Conceptual syntax and Use cases
Initially the code looks like this
match expression:
case 1:
return True
case 2:
return True
case 3:
return True
...
case _:
return False
The return True
statement gets repeated many times here.
In this situation, one possible question might be “why not just use an if statement instead?”. But imagine there are more statements to the switch statement, which are executing different blocks of code and not just
return True
, then we can’t just go for if-else statements. The match statement would make the code look a lot cleaner too!
The new syntax shall help to group all the cases having similar block of code to execute, by omitting statement blocks for the first cases. The idea is to allow to have multiple case patterns for one section of a match
statement.
match expression:
case 1:
case 2:
case 3:
...
return True
case _:
return False