Multiple case patterns for one section (structural pattern matching)

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

This already exists, spelled a bit differently:

match expression:
    case 1 | 2 | 3:
        return True
    case _:
        return False

See the documentation for “OR patterns”.

1 Like

Oh me my bad! I didn’t check the docs properly. Really sorry I am, and thank you for pointing out! :handshake:
Please let me know if there is a way to close this topic since its resolved now.