Q:

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

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:
  # 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 raise 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 who usually in other programming language don't execute the code in the case unless it's a match.
is there an other way to do this or i just need to do if elif ... 
Update:
  thank you for all the replies, but 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 on an other pattern .

A:

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=''
    ...

A:

It sounds like you're complicating this more than you need to. You want simple?
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.

A:

Turns out the jokes on me and I was pwned in the switch inventing game 5 years before I even learned python: Readable switch construction without lambdas or dictionaries. Oh well. Read below for another way to do it.

Here. Have a switch statement.  (with some nice cleanups by @martineau)
with switch(foo):

    @case(1)
    def _():
        print "1"

    @case(2)
    def _():
        print "2"

    @case(3)
    def _():
        print "3"

    @case(5)
    @case(6)
    def _():
        print '5 and 6'

    @case.default
    def _():
        print 'default'

I'll toss in the (moderately) hacked stack, abused decorators and questionable context manager for free. It's ugly but functional (and not in the good way). Essentially, all it does is wrap the dictionary logic up in an ugly wrapper. 
import inspect

class switch(object):
    def __init__(self, var):
        self.cases = {}
        self.var = var

    def __enter__(self):
        def case(value):
            def decorator(f):
                if value not in self.cases:
                    self.cases[value] = f
                return f
            return decorator

        def default(f):
            self.default = f
            return f
        case.default = default 

        f_locals = inspect.currentframe().f_back.f_locals
        self.f_locals = f_locals.copy()
        f_locals['case'] = case

    def __exit__(self, *args, **kwargs):
        new_locals = inspect.currentframe().f_back.f_locals
        new_items = [key for key in new_locals if key not in self.f_locals]
        for key in new_items:
             del new_locals[key]              # clean up
        new_locals.update(self.f_locals)      # this reverts all variables to their
        try:                                  # previous values
            self.cases[self.var]()
        except KeyError:
            try:
                getattr(self, 'default')()
            except AttributeError:
                pass

Note that the hacked stack isn't actually necessary. We just use it to create a scope so that definitions that occur in the switch statement don't leak out into the enclosing scope and to get case into the namespace. If you don't mind leaks, (loops leak for instance), then you can remove the stack hack and return the case decorator from __enter__, using the as clause on the with statement to receive it in the enclosing scope.

