Main Content

No switch in Python

Archive - Originally posted on "The Horse's Mouth" - 2007-05-23 18:09:58 - Graham Ellis

Question There's no switch statement in Python. Why not?

(Poor) Answer Because there's no need .. you can use a series of if and elif statments. And we can't do it in Python because there isn't a label syntax that would be needed for case.

Better Answer If you come to write some code where a switch would be your natural choice in another language, then you would probably do far better to be using a set of polymorphic methods on various types of objects in Python.

What you might do without objects (a poor switch replacement):

if type == "local":
  name = "localhost"
elif type == "file":
  name = namevar
else:
  name = geturl()


What you would write with classes local, file and remote predefined:

name = current.getname()