简体   繁体   中英

Switch-Case alternative in Python except dictionary

I have nested if-else statements and each condition call a different function. something like --

var = "somestring"
if var == 'call':
    if var2 == 'someothercomparison':
        return func1(arg1, arg2)
    elif var2 == 'otherway':
        return func2()
elif var == 'sms':
    return func3(arg3)
elif var == 'mail':
    return func4(arg4)

this is just a sample data.. there are many more elif .

If I try to use dictionary then it would become inefficient as then complier/interpreter will try to execute all functions to validate dictionary syntax. So I cannot use dictionary.

Is there any other elegant/classy/pythonic way to do this task?

You can use a dict of dicts with functions and arguments as values:

def func1(s):print(s)
def func2(s):print(s)
def func3(s):print(s)
def func4(s):print(s)

d = {"call":{'someothercomparison': (func1,"arg1"),'otherway':(func2,"arg2")},"sms":(func3,"arg3"),"mail":(func4,"func4")}

var = "call"
var2 = 'otherway'

def main(var,var2):
    f = d.get(var, {}).get(var2)
    if f:
       return  f[0](f[1])
    f = d.get(var)
    if f:
        return  f[0](f[1])
    return whatever

You can exploit a combination of dictionaries and lambdas:

options={"a":lambda:doA(arg1,arg2),"b":lambda:doB(arg3,arg4)}
options[var]()

If you need a default:

from collections import defaultdict
options=defaultdict(lambda:lambda:doDefault(arg1,arg2),options)

Do do branching, just have the lambda do it:

def branch1():
    if cond:
      doA()
    else:
      doElse(args)
options={"abc":lambda:branch1()}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM