Please explain why Python does not have the switch-case feature implemented in it.
Unlike every other programming language we have used before, Python does not have a switch or case statement.
A switch case statement is a multi-branched statement which compares the value of a variable to the values specified in the cases. Python does not have a switch statement but it can be implemented using other methods, which will be discussed below.
getattr() in Python is used to invoke a function call. The lambda keyword in Python is used to define an anonymous function. In case the user gives an invalid input, lambda will invoke the default function.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With