Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch-case in Python doesn't work; need another pattern

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.

like image 357
Unknown Avatar asked Nov 28 '22 12:11

Unknown


2 Answers

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=''
    ...
like image 115
unutbu Avatar answered Dec 14 '22 22:12

unutbu


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.

like image 37
Kirk Strauser Avatar answered Dec 14 '22 22:12

Kirk Strauser