We're back after a server migration that caused effbot.org to fall over a bit harder than expected. Expect some glitches.

Why isn't there a switch or case statement in Python?

You can do this easily enough with a sequence of if and elif statements. There have been some proposals for switch statement syntax, but there is no consensus (yet) on whether and how to do range tests, and more importantly, when and how to evaluate constant case expressions. See PEP 275 for some background.

For cases where you need to choose from a very large number of possibilities, you can create a dictionary mapping case values to functions to call. For example:

def function_1():
    print "1"

functions = {
    'a': function_1,
    'b': function_2, 
    'c': self.method_1,
     # ...
}

func = functions[value]
func()

For calling methods on objects, you can simplify yet further by using the getattr built-in to retrieve methods with a particular name:

class MyClass:

    def visit_a(self):
        print "A"

    def visit_b(self):
        print "B"

    # ...

    def dispatch(self, value):
        method_name = 'visit_' + str(value)
        try:
            method = getattr(self, method_name)
        except AttributeError:
            print method_name, "not found"
        else:
            method()

It’s suggested that you use a prefix for the method names, such as “visit_” in this example. Without such a prefix, if values are coming from an untrusted source, an attacker would be able to call any method on your object.

CATEGORY: general

CATEGORY: design