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

后端 未结 9 1523
臣服心动
臣服心动 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条回答
  •  被撕碎了的回忆
    2020-12-10 21:17

    message = { 'create':msg(some_data or ''),
                'update':msg(other_data or '')
                # can have more
              }
    

    Better yet, to prevent msg from being executed just to fill the dict:

    message = { 'create':(msg,some_data),
                'update':(msg,other_data),
                # can have more
              }
    func,data=message[msg_type]
    func(data)
    

    and now you are free to define a more sensible msg function which can deal with an argument equal to None:

    def msg(data):
        if data is None: data=''
        ...
    

提交回复
热议问题