Why doesn't Python have switch-case? Why doesn't Python have switch-case? python python

Why doesn't Python have switch-case?


Update: New syntax (which goes beyond a simple case statement) has been accepted for inclusion in Python 3.10, see PEP 634 Structural Pattern Matching: Specification.


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


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.


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