iskandar suhaimi
iskandar suhaimi

Reputation: 75

Python3 Switch not working, return all case

i'm new with python, i try to make a switch-case implementation in python, I already found out about this but its not working. it return all of this case

if not (data.message is None):
    if data.message[0] == "/":
        command = data.message.split("/")
        if not (command[1] is None):
            switcher = {
                "location" : funcA(data.id),
                "carousel" : funcB(data.id, data.name),
                "button" : funcC(data.id),
                "card" : funcD(data.id, data.name)
            }
            return switcher.get(command[1], funcE())
        else:
            return funcE()
    else:
        return funcE() 

then, i test input command[1] with '/asd' , it will return all of function.

Upvotes: 1

Views: 413

Answers (1)

glhr
glhr

Reputation: 4537

As @snakecharmerb mentioned, in your dictionary values, you should be naming the functions not calling them:

switcher = {
    "location" : funcA,
    "carousel" : funcB,
    "button" : funcC,
    "card" : funcD
}

And specify the argument data.id in the return statement, if the key exists in the dictionary:

return switcher[command[1]](data.id) if command[1] in switcher else funcE()

Also, you can replace if not (data.message is None) with if message and combine it with data.message[0] == "/".

As pointed out by @Mark Bailey, since you're already checking if command[1] is in switcher, you can remove the second if statement altogether.

All in all:

if data.message and data.message[0] == "/":
    command = data.message.split("/")
    switcher = {
        "location" : funcA,
        "carousel" : funcB,
        "button" : funcC,
        "card" : funcD
    }
    return switcher[command[1]](data.id) if command[1] in switcher else funcE()
else:
    return funcE()

Edit: To support passing a variable number of arguments to the functions, you can specify an argument list in the dictionary, and pass it to the function with unpacking:

if data.message and data.message[0] == "/":
    command = data.message.split("/")
    switcher = {
        "location" : [funcA,[data.id,data.name]],
        "carousel" : [funcB,[data.id]],
        "button" : [funcC,[data.id,data.name]],
        "card" : [funcD,[data.id,data.name, data.time]]
    }
    return switcher[command[1]][0](*switcher[command[1]][1]) if command[1] in switcher else funcE()
else:
    return funcE()

Upvotes: 1

Related Questions