4

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.

4
  • 1
    at the very least, square brackets for indexing: return message[type] Commented Oct 8, 2010 at 13:21
  • 2
    it's traditional to accept an answer if there's one you like. Commented Oct 8, 2010 at 23:02
  • with all my respect to the people that help me here, i didn't like any solution maybe next time if i found another use of switch case i will write a pep and try to get it accepted , like that we will have a "real" switch case statement. Commented Oct 10, 2010 at 3:56
  • The canonical is Replacements for switch statement in Python? [sic]. It also has the switch statement introduced with Python 3.10 (2021). Commented Oct 5, 2021 at 11:24

9 Answers 9

9
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=''
    ...
Sign up to request clarification or add additional context in comments.

19 Comments

@Unknown, if that code looks unreadable, you need to learn to read better. This is the cleanest code you will find for this and nicely uses the fact that functions are first class objects.
@Unkown. Sorry. I could be kidnapped by organ harvesters and read that code while drugged for an operation X months after writing it. If anybody in your company couldn't read that, then it just makes me pissed that they get to write code for a living and I don't. It's really trivial stuff.
If you're going to write code for the lowest possible denominator, then you're always going to have this issue, even if the code is readable and Pythonic.
@Unknown: at some point, you really have to assume a basic level of knowledge with the programming language in use. If the code uses an esoteric part of the language, you can add a comment, but that code isn't really all that unreadable, and I'm not all that much of a python guy.
@Unknown: that dictionaries can be used this way is basic knowledge of Python. The language hasn't got a switch statement because you can either use if / elifs or this construct. I'd say your company needs to invest a bit more in employee training and interviewing if you work in python and can't fathom or remember that functions are first-class objects and dicts are very versatile.
|
9

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.

3 Comments

@jathanism : sorry but i don't agree; try to do if/else with more condition it's definitely slower, and it's in condition like this where the switch/case come in hand , i don't want to start a complain but this is what i hate in python the fact that some functionality are missing ((real)thread, switch/case ..) and when you want to use them you have to do some hack to replace them (processes , dictionary ...) and it's never the same , with all my respect
@Unknown: you can't know that unless you've benchmarked it. In an idealized situation where you can set up your dictionary once and then reuse it many times, and there are enough potential branches to incur noticeable overhead, the dict approach may be faster. If those aren't all true, and you can optimize your if/elif block so that the most common condition is tested first, it may actually be slower.
Some Guy: what i actually said was that if else is slower than a switch case in language that implement it "in many cases"
4

Turns out the jokes on me and I was pwned in the switch inventing game five 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.

15 Comments

Dear God. I gave you +1 for commendable insanity.
+1 for creative abuse of with and decorators -- but I doubt the OP would like it give he/she thought func,data=message[msg_type] was overly complicated.
FWIW, if you moved the self.f_locals = copy.copy(f_locals) up one line in __enter(), you wouldn't need the del new_locals['case'] in __exit__().
Easily fixed bug. The nested decorator(f) function needs a return f at the end so the chaining of @case(X) decorators works -- otherwise setting foo = 5 results in a TypeError: 'NoneType' object is not callable error in the example. Nonetheless, a very clever solution.
@martineau, thanks for the fixes. The last bug was just a copying error resulting from editing two versions at once. Embarrassed I missed the first one though. Oh well, I probably should have been sleeping when I was writing this so I'll let that explain it. The point is not that OP like it but that OP see a complicated solution to the problem to put the simple ones in perspective.
|
3

Here's something a little different (although somewhat similar to @Tumbleweed's) and arguably more "object-oriented". Instead of explicitly using a dictionary to handle the various cases, you could use a Python class (which contains a dictionary).

This approach provides a fairly natural looking translation of C/C++ switch statements into Python code. Like the latter it defers execution of the code that handles each case and allows a default one to be provided.

The code for each switch class method that corresponds to a case can consist of more than one line of code instead of the single return <expression> ones shown here and are all compiled only once. One difference or limitation though, is that the handling in one method won't and can't be made to automatically "fall-though" into the code of the following one (which isn't an issue in the example, but would be nice).

class switch:
    def create(self): return "blabla %s" % msg(some_data)
    def update(self): return "blabla %s" % msg(other_data)
    def delete(self): return "blabla %s" % diff(other_data, some_data)
    def _default(self): return "unknown type_"
    def __call__(self, type_): return getattr(self, type_, self._default)()

switch = switch() # only needed once

return switch(type_)

Comments

2

You could hide the evaluation inside a lambda:

message = { 'create': lambda: msg(some_data),
            'update': lambda: msg(other_data),
          }
return message[type]()

As long as the names are all defined (so you don’t get a NameError), you could also structure it like this:

message = { 'create': (msg, some_data),
            'update': (other_func, other_data),
          }
func, arg = message[type]
return func(arg)

1 Comment

sorry , but not all of the cases use msg()
1

You can delay execution of the match using lambda:

return {
    'create': lambda: msg(some_data),
    'update': lambda: msg(other_data),
    # ...
}[type]()

If all the cases are just calling msg with different arguments, you can simplify this to:

return msg({
    'create': some_data,
    'update': other_data,
    # ...
}[type])

Comments

1

Create a new class and wrap the data/arguments in an object - so instead of binding data by passing arguments - you could just let a function decide which parameters it needs...

class MyObj(object):
    def __init__(self, data, other_data):
        self.data = data
        self.other_data = other_data

    def switch(self, method_type):
        return {
                   "create": self.msg,
                   "update": self.msg,
                   "delete": self.delete_func,
                }[method_type]()

    def msg(self):
        # Process self.data
        return "Hello, World!!"

    def delete_func(self):
        # Process other data self.other_data or anything else....
        return True

if "__main__" == __name__:
    m1 = MyObj(1,2)
    print m1.switch('create')
    print m1.switch('delete')

Comments

0

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

Comments

0

Ah never mind, this explained it. I was thinking of elif - Switch-case statement in Python

3 Comments

sorry, if i didn't mention that but it's python , and python don't have one
Yeah, I remembered after I hit submit and looked at my old code. Haven't used python in a while and I was only fundamental really
A switch statement was introduced with Python 3.10 (2021).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.