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:<
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')