-3

How can we exit the match-case statement ahead of time?
Is it even possible?
break and continue are only possible within loops

test = "b"
match test:
    case "a":
        print("a")
    case "b":
        print("b")
        if early_exit_condition_reached:
            break # invalid: "break" can be used only within a loop
        print("c")
    case "d":
        print("d")

The goal is to avoid multiple if statements or nested if clauses once it is clear that the task is done.

ATH
  • 666
  • 6
  • 13

1 Answers1

1

There is no need for it - once case "b" matches, the other case clauses are not checked, nor any code in a case block is run.

In other words: unlike C's original switch...case syntax, each case block in Python's match...case is independent, and after the case block ends, execution jumps to the end of the match block.

If in the snippet above you don't want to run the print("c") line, just don't put it there. If it is more complex, and print("c") depend on another condition that may or not be reached once "b" is matched, add an if statement inside the case block. There is no break or continue equivalent that would skip the remainder of the block: the conditional code must itself be guarded by the if clause.

test = "b"
match test:
    case "a":
        ...
    case "b":
        print("b")
        if condition_to_print_c:
            print("c")
    case "d":
        ...

Or, you can adopt this style, but it will lead to duplication of the common parts:

test = "b"
match test:
    case "a":
        ...
    case "b" if condition_to_print_c:   # guard clause includes extra condition
        print("b")
        print("c")
    case "b":
        print("b")  # this part must be duplicated in both clauses
    case "d":
        ...

Otherwise, one can always use raise and return statements inside case blocks: it will "skip the remainder of the case block" but any coded like that will hardly be more readable or maintainable - unless said statement is the last one in a case block, aborting the execution of the remainder of the function as a whole.

jsbueno
  • 99,910
  • 10
  • 151
  • 209
  • Well, congrats, you just made me re-read it and double check. It is correct. If there is any particular statement in there that you think could be more clear, please be specific. – jsbueno Jun 14 '23 at 15:38