W3docs

Replacements for switch statement in Python?

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

Here are a few alternatives to using a switch statement in Python. Historically, Python lacked a native switch statement, but Python 3.10 introduced the match/case statement as the official replacement. Below are common alternatives, including the modern approach and traditional workarounds:

  1. match/case statement (Python 3.10+): You can use the match/case statement to achieve pattern matching and switch-like behavior. For example:

match/case statement in Python

def f(x):
    match x:
        case 1:
            return 1
        case 2:
            return 2
        case 3:
            return 3
        case _:
            return "Something else"

print(f(4))
  1. If-elif-else chain: You can use an if-elif-else chain to achieve the same effect as a switch statement. For example:

An if-elif-else chain in Python

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

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

  1. Dictionary mapping: You can use a dictionary to map values to functions or expressions. For example:

Dictionary mapping to replace switch statements in Python

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

The switch.get(x, lambda: "Something else")() syntax looks up x in the dictionary. If x is not found, it returns the default lambda function, and the trailing () immediately calls it.

  1. Object-oriented approach: If you are using an object-oriented programming style, you can encapsulate the logic in a class. Note that Python does not support traditional function or method overloading, so this simply uses an if-elif-else chain inside a class method. For example:

Use an object-oriented approach to replace switch statements in Python

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