Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Python have switch-case?

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

like image 861
T1412 Avatar asked Oct 12 '17 03:10

T1412


People also ask

Do switch cases exist in Python?

Unlike every other programming language we have used before, Python does not have a switch or case statement.

Does Python have switch case statement True False?

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.

What is the alternative for switch in Python?

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.


2 Answers

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

like image 103
Raymond Hettinger Avatar answered Oct 06 '22 00:10

Raymond Hettinger


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.

like image 36
wim Avatar answered Oct 05 '22 22:10

wim