Replacements for switch statement in Python?

Here are a few alternatives to using a switch statement in Python:

  1. If-elif-else chain: You can use an if-elif-else chain to achieve the same effect as a switch statement. For example:
def f(x):
    if x == 1:
        return 1
    elif x == 2:
        return 2
    elif x == 3:
        return 3
    else:
        return "Something else"

print(f(4))

Watch a course Python - The Practical Guide

  1. Dictionary mapping: You can use a dictionary to map values to functions or expressions. For example:
def f(x):
    def g():
        return "Function g"
    
    def h():
        return "Function h"
    
    def i():
        return "Function i"
    
    switch = {
        1: g,
        2: h,
        3: i
    }
    
    return switch.get(x, lambda: "Something else")()

print(f(3))
  1. Function or method overloading: If you are using a object-oriented programming style, you can use function or method overloading to achieve a similar effect to a switch statement. For example:
class MyClass:
    def f(self, x):
        if x == 1:
            return self.g()
        elif x == 2:
            return self.h()
        elif x == 3:
            return self.i()
        else:
            return "Something else"
    
    def g(self):
        return "Method g"
    
    def h(self):
        return "Method h"
    
    def i(self):
        return "Method i"

obj = MyClass()
print(obj.f(2))