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:
match/casestatement (Python 3.10+): You can use thematch/casestatement 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))- If-elif-else chain: You can use an if-elif-else chain to achieve the same effect as a
switchstatement. 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">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
- 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 upxin the dictionary. Ifxis not found, it returns the default lambda function, and the trailing()immediately calls it.
- 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-elsechain 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))