Since I started developing with python I never found myself in the need of such statement. As I remember I never asked where is the switch statement in this language. I think I never asked that because of the dictionary data type in python that you can use to do the same thing as a switch statement will do. I was surprised that there are many PEPs about adding the switch statement to python.
In other languages the switch statement looks like this:
in python one can do the same thing with the help of a dictionary like this:
Here is link to a post where there are many comments that try to come up with an alternative:
http://simonwillison.net/2004/May/7/switch/
Why should python have a switch statement when there is a more powerful way to do the same with a dict data type ?
Should Python also have a GOTO ?
In other languages the switch statement looks like this:
switch (var)
{
case value1: do_some_stuff1();
case value2: do_some_stuff2();
...
case valueN: do_some_stuffN();
default: do_default_stuff();
}
in python one can do the same thing with the help of a dictionary like this:
values = {
value1: do_some_stuff1,
value2: do_some_stuff2,
...
valueN: do_some_stuffN,
}
values.get(var, do_default_stuff)()
Here is link to a post where there are many comments that try to come up with an alternative:
http://simonwillison.net/2004/May/7/switch/
Why should python have a switch statement when there is a more powerful way to do the same with a dict data type ?
Should Python also have a GOTO ?
31 Jul 2007 23:02:36
Well, for one thing lambdas can't seem to print. For example this doesn't work:
result = {
1 : lambda : print "value is 1",
2 : lambda : print "value is 2"
}
result.get(2, lambda: print "nothing")
Switch statements are far more flexible than the dictionary type for executing arbitrary code.
01 Aug 2007 19:25:17
You'r right. lambda cannot print because:
1. lambda cannot contain statements: http://docs.python.org/ref/...
2. if you want to print with lambda: http://www.p-nand-q.com/pyt...
To make the example you wrote work, remove "print" from all lambda and put a "print" before result.get
17 Mar 2008 16:52:56
What about different function signatures? How would you translate the following, for example?
switch( var )
case1: printStr( 'Hello!' );
case2: printError();
06 Apr 2008 01:13:55
A large part of the power of switch statements is that a matching case is run AND so is every case after the matching case until a break statement is encountered. Additionally, switch statements have a default case which runs if there was no matching case or if there was no break after a matching case. The lambda hacks miss these useful features. I think PHP's implementation of switch is quite nice.