Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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):
    c = 0
    match x:
        case "Hello,":
            a()
            c = 1
        case "World!":
            b()
            c = 1
        case "foobar":
            c()
            c = 1
    if c == 1:
        print("Something happened")
    else:
        print("Something didn't happen :(")

I could also run my function in every case:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        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'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading