Why doesn't Python have switch-case?
PythonSwitch StatementPython Problem Overview
Please explain why Python does not have the switch-case feature implemented in it.
Python Solutions
Solution 1 - Python
Update 2021:
New match-case syntax, which goes far beyond the capabilities of the traditional switch-case syntax, was added to Python in version 3.10. See these PEP documents:
- PEP 634 Structural Pattern Matching: Specification
- PEP 635 Structural Pattern Matching: Motivation and Rationale
- PEP 636 Structural Pattern Matching: Tutorial
We considered it at one point, but without having a way to declare named constants, there is no way to generate an efficient jump table. So all we would be left with is syntactic sugar for something we could already do with if-elif-elif-else chains.
See PEP 275 and PEP 3103 for a full discussion.
Roughly the rationale is that the various proposals failed to live up to people's expections about what switch-case would do, and they failed to improve on existing solutions (like dictionary-based dispatch, if-elif-chains, getattr-based dispatch, or old-fashioned polymorphism dispatch to objects with differing implementations for the same method).
Solution 2 - Python
There is literally a section in the docs to answer this. See below:
Why isn’t there a switch or case statement in Python?
TL;DR: existing alternatives (dynamic dispatch via getattr
or dict.get
, if
/elif
chains) cover all the use cases just fine.
Solution 3 - Python
def f(x):
return {
1 : 'output for case 1',
2 : 'output for case 2',
3 : 'output for case 3'
}.get(x, 'default case')
You can use this as switch case in python and if condition not match it will return default if condition not match
Solution 4 - Python
Update 2021: case
introduced in Python 3.10
Structural pattern matching is included in Python 3.10 released in October 2021.
Here is the generic syntax
match subject:
case <pattern_1>:
<action_1>
case <pattern_2>:
<action_2>
case <pattern_3>:
<action_3>
case _:
<action_wildcard>
and here is a simple example
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the Internet"
Solution 5 - Python
I remembered in ancient time, an inexperienced Larry Walls said that Perl doesn't need case switch construct because it can be done the same way with: "if - elif - elif .... else". Back then Perl was nothing more but a mere scripting tool for hacker kiddies. Of course, today's Perl has a switch construct.
It's not unexpected that over some decades later, the new generation kids with their new toys are doomed to repeat the same dumb statement.
It's all about maturity, boys. It will eventually have a case construct. And when python has matured enough as a programming language, like FORTRAN/Pascal and C and all languages derived from them, it will even have a "goto" statement :)
BTW. Usually, case switch translated to asm as indirect jump to list of address of respective cases. It's an unconditional jump, means far more efficient than comparing it first (avoiding branch misprediction failure), even in just a couple cases it considered as more efficient. For a dozen or more (up to hundreds in code snippet for a device driver) the advantage of the construct is unquestionable. I guess Larry Walls didn't talk assembly back then.
Solution 6 - Python
Actually, Python does not have a switch case, and you need to use the Class method which is explained somehow like this.
class PythonSwitch:
def day(self, dayOfWeek):
default = "Incorrect day"
return getattr(self, 'case_' + str(dayOfWeek), lambda: default)()
def case_1(self):
return "monday"
def case_2(self):
return "tuesday"
def case_3(self):
return "wednesday"
def case_4(self):
return "thursday"
def case_5(self):
return "friday"
def case_7(self):
return "saturday"
my_switch = PythonSwitch()
print (my_switch.day(1))
print (my_switch.day(3))def case_6(self):
return "sunday"
my_switch = PythonSwitch()
print (my_switch.day(1))
print (my_switch.day(3))
But this is not good way and python documentation suggest you use to Dictionary method.
def monday():
return "monday"
def tuesday():
return "tuesday"
def wednesday():
return "wednesday"
def thursday():
return "thursday"
def friday():
return "friday"
def saturday():
return "saturday"
def sunday():
return "sunday"
def default():
return "Incorrect day"
switcher = {
1: monday,
2: tuesday,
3: wednesday,
4: thursday,
5: friday,
6: saturday,
7: sunday
}
def switch(dayOfWeek):
return switcher.get(dayOfWeek, default)()
print(switch(3))
print(switch(5))
Instead of match the style which does not include default value. <https://docs.python.org/3.10/whatsnew/3.10.html#pep-634-structural-pattern-matching>
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"
But in 2020 there is new 'Enum-based Switch for Python''https://pypi.org/project/enum-switch/';
from enum import Enum
from enum_switch import Switch
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
class MySwitch(Switch):
def RED(self):
return "Apple"
def GREEN(self):
return "Kiwi"
def BLUE(self):
return "Sky"
switch = MySwitch(Color)
print(switch(Color.RED))
Apple
If MySwitch was missing one of those "handlers" for the Enum values? That's an exception. If you don't want to define them all? Do a default() there.