T1412
T1412

Reputation: 755

Why doesn't Python have switch-case? (Update: match-case syntax was added to Python 3.10 in 2021)

Please explain why Python does not have the switch-case feature implemented in it.

Upvotes: 71

Views: 50473

Answers (8)

Ehsan Paknejad
Ehsan Paknejad

Reputation: 708

You have multiple options for switch in python:

1- match case:

match status:
    case 400:
        return "Bad request"
    case 404:
        return "Not found"
    case 418:
        return "I'm a teapot"

    # If an exact match is not confirmed, this last case will be used if provided
    case _:
        return "Something's wrong with the internet"

2- if elif else

3- My favorate. Sometimes you can use it:

return ['kid','teenager','adult','elderly'][(age>12)+(age>17)+(age>64)]

First level are values and second level are keys (0, 1, 2, or 3)

Upvotes: 0

Rhyous
Rhyous

Reputation: 6690

Why would any modern language support a switch/case statement?

It is like the goto statement. It is an outdated construct, that when following SOLID and good design pratices, just shouldn't get used. It was useful at one time, but as we matured in SOLID and other design patterns, it became clear that it was less effective.

I am a C# developer primarily, but I hit python, TypeScript, and other languages now and then and I haven't used Switch/case in almost a decade. Every single opportunity to use switch case leads to bad cade that is not SOLID and has high Cyclomatic complexity.

Python mentions using a dictionary, which is right in line with what I recommend in C#. https://www.rhyous.com/2017/10/19/eliminating-cylclomatic-complexity-by-replacing-switchcase-with-a-method-or-a-dictionary/

Upvotes: -3

divenex
divenex

Reputation: 17256

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"

Upvotes: 10

Raymond Hettinger
Raymond Hettinger

Reputation: 226694

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:


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

Upvotes: 82

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 miss­ing one of those "han­dler­s" for the Enum val­ues? That's an ex­cep­tion. If you don't want to de­fine them al­l? Do a de­fault­() there.

Upvotes: -1

user6801759
user6801759

Reputation: 125

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.

Upvotes: 5

vedant patel
vedant patel

Reputation: 105

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

Upvotes: 8

wim
wim

Reputation: 363486

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.

Upvotes: 14

Related Questions