« Training information - England, Scotland, Wales and Ireland | Main | Returning multiple values from a function (Perl, PHP, Python) »

May 23, 2007

No switch in Python

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

Posted by gje at May 23, 2007 06:09 PM

Comments

Post a comment




Remember Me?


Well House Consultants Ltd. Copyright 2008