switch case in python doesn't work; need another pattern

后端 未结 9 1507
臣服心动
臣服心动 2020-12-10 20:28

I need a help with a code here, i wanted to implement the switch case pattern in python so like some tutorial said , i can use a dictionary for that but here is my problem:<

9条回答
  •  Happy的楠姐
    2020-12-10 21:07

    Since the code you want to execute in each case is from a safe source, you could store each snippet in a separate string expression in a dictionary and do something along these lines:

    message = { 'create': '"blabla %s" % msg(some_data)',
                'update': '"blabla %s" % msg(other_data)',
                'delete': '"blabla %s" % diff(other_data, some_data)'
              }
    
    return eval(message[type_])
    

    The expression on the last line could also be eval(message.get(type_, '"unknown type_"')) to provide a default. Either way, to keep things readable the ugly details could be hidden:

    switch = lambda type_: eval(message.get(type_, '"unknown type_"'))
    
    return switch(type_)
    

    The code snippets can even be precompiled for a little more speed:

    from compiler import compile # deprecated since version 2.6: Removed in Python 3
    
    for k in message:
        message[k] = compile(message[k], 'message case', 'eval')
    

提交回复
热议问题