Why doesn't Python have switch-case?

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


Solution 1:

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:

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:

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