I need a help with some 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:
# Type can be either create or update or ..
message = { 'create':msg(some_data),
'update':msg(other_data)
# can have more
}
return message(type)
but it's not working for me because some_data or other_data can be None (it raises an error if it's none) and the msg function need to be simple (I don't want to put some condition in it).
The problem here is that the function msg() is executed in each time for filling the dict.
Unlike the switch case pattern which usually in other programming language don't execute the code in the case
unless it's a match.
Is there another way to do this or do I just need to do if elif?
Actually, it's more like this:
message = { 'create': "blabla %s" % msg(some_data),
'update': "blabla %s" % msg(other_data)
'delete': "blabla %s" % diff(other_data, some_data)
}
So lambda don't work here and not the same function is called, so it's more like a real switch case that I need, and maybe I have to think about another pattern.
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=''
...
It sounds like you're complicating this more than you need to. If you want it simple, use:
if mytype == 'create':
return msg(some_data)
elif mytype == 'update':
return msg(other_data)
else:
return msg(default_data)
You don't have to use dicts and function references just because you can. Sometimes a boring, explicit if/else
block is exactly what you need. It's clear to even the newest programmers on your team and won't call msg() unnecessarily, ever. I'm also willing to bet that this will be faster than the other solution you were working on unless the number of cases grows large and msg() is lightning fast.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With