pythonpython-3.xswitch-statementpython-3.10any

Shorter way to execute some code if any case were matched Python 3.10


I have a match...case... loop set up, and I want to run some code if any one of the cases were matched. I figured I could just do this by having a designated variable like in the following, but I wondered if there was a shorter way to do it, as this seems to be excessively verbose.

Here's some example code that does, in a nutshell, what I need to do:

def foo(x):
    go = 0
    match x:
        case "Hello,":
            a()
            go = 1
        case "World!":
            b()
            go = 1
        case "foobar":
            c()
            go = 1
    if go == 1:
        print("Something happened")
    else:
        print("Something didn't happen :(")

I could also run my function in every case:

        case "Hello,":
            a()
            print("Something happened")
(etc...)

But again, this seems redundant and I wanted to know if there was a more elegant solution.


Solution

  • my 2cts

    def a():
        print("On 'a' func")
    
    def b():
        print("On 'b' func")
    
    def c():
        print("On 'c' func")
    
    def foo(x):
        if x in cmd:
            cmd[x]()
            print(f"Something happened on '{x}': {cmd[x]}")
        else:
            print(f"Something didn't happen :( on '{x}'")
    
    cmd = {"Hello,": a, "World!": b, "foobar": c}
    
    foo("World!")
    
    foo("bar")
    
    On 'b' func
    Something happened on 'World!': <function b at 0x7fd52fe653a0>
    Something didn't happen :( on 'bar'