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.
29 Jan 2009 22:03:05
I know that this was posted forever ago, but my answer to "Why should python have a switch statement when there is a more powerful way to do the same with a dict data type?" is to ask another question:
"Why should python have an IF statement when there is a more powerful way to do the same with a dict data type?"
def foo():
print "foo"
def bar():
print "bar"
values = {
True: foo,
False: bar
}
>>> values.get(1==1)()
foo
>>> values.get(1!=1)()
bar
Orthogonality of your language *is* arguably a desirable quality to have, but only to a point. I think you'd be hard-pressed to find someone to argue the above is correct. What makes switch different?
08 Apr 2009 20:51:48
Python should never have a GOTO. Definitely.
18 Apr 2009 14:58:51
I'm looking for a technique that will let me make case/switch ASSIGNMENTS on the fly; eg.
case(x = "red"):
name = "apple"
case(x = "blue"):
name = "blueberry"
case(x = "pink"):
name = "...watermellon?"
return "Your fruit is",name<ctrl-s>[habit:)]
Anyway, my point: I can bind dictionary- and lambda-embedded functions to COMPUTATIONS(eg. if x = 1, return 2*3), but not to ASSIGNMENTS (eg. if x = 1, name = "red").
Suggestions?
25 May 2009 23:46:25
John,
fruits = {
"red": lamdba: "apple",
"blue": lambda: "blueberry",
"pink": lambda: "watermelon"
}
name = fruits.get("red")()
print "Your fruit is " + name
You can also do the same thing by changing (for instance) this
lambda: "apple"
into this
do_apple()
and then making a function like this
do_apple():
global name
name = "apple"
return apple
(the 'return apple' is optional).
This problem isn't python specific, it's more a generic problem of scope which you'll encounter in any language that cleans up function variables. Even C won't let you call a local variable globally unless you tell it to.
13 Dec 2009 04:53:35
here is the reason why they need to add a switch statement: that does not work, (or atleast it didn't for me), and it's confusing, they are supposed to be variables, not commands, I honestly don't see how that could possibly have run the code in the condition parts
13 Dec 2009 04:54:23
what's lambda?
03 Jan 2010 00:55:34
John,
Just replace 'case' in your code with 'if'.
09 Jan 2010 07:03:52
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.
20 Mar 2010 14:43:06
There are no 'while' loops in Scheme because you're expected to use recursion for looping effects. That makes sense, it's built into the structure of the language. Using dictionaries as a substitute for a switch statement is just that: a substitution of a part of the language that manifestly was not intended to be used as a conditional statement, in order to get around the fact that there is no 'switch' conditional.
Using dictionaries in this manner strikes me as inelegant and implausible. Since the designers of python created a language it which it is not possible to use a 'switch' statement, it seems more to the point to acknowledge that if you're trying to figure out how to shoehorn a 'switch' into your programming, you're not thinking in the python paradigm. You're thinking like a C or Java programmer. So: what is the Python paradigm and how does it achieve the goals of a 'switch' statement without implementing one?
17 Jun 2010 16:25:23
Its actually pretty simple: Theres NO switch in Python and theres NO alternative.
Is this bad? Yes it is.
I'm really sick of those language fanboys that couldn't admit the simple truth.
02 Jul 2010 04:30:31
The last comment is the most important on this thread: substituting the switch statement on your Python code depends on what you want to do; if it is to select a value from a variety of possible inputs, a dict could be a pythonic solution; for other problems it might not.
23 Jul 2010 11:36:52
Along with all of the other more detailed answers, I would add that a switch statement is simply unnecessary as one of the core ideas of the python language is that there should be one obvious way to do something.
06 Nov 2010 14:24:20
What a wonderful trail... three years long.
Forty years and dozens of languages. I enjoy Python because it tends to eliminate artifice more than other languages (e.g. no primitives, just objects)
Python DOES have a simple alternative. It's the original: if then [else [if]]
Gosh, that's the way we used to do it. The switch statement provides some extra clarity, type safety in languages that care, and the ability of the compiler to optimize dispatching of the code to execute.
Because of this, it would be nice if Python had a switch statement, but it's not really an imperative is it?
02 Dec 2010 22:40:51
If then elseif is so primative and in my programming case it's making my code LONG!
I love cases, I love the fact you don't have to fart-ar$e around and repeat sections of code that you may have to in if statements.
Personally I think Python is behind the 8 ball when it comes to this simple programming funtion.
06 Dec 2010 14:39:22
Hi,
If you're searching extra-statement, as "switch", I've just built a python module that extends Python. It's called ESPY as Enhanced Structure for Python and it's available for both Python 2.x and Python 3.x.
For example, in this case, a switch statement could be performed by the following code:
"""
macro switch(arg1):
while True:
cont=False
val=%arg1%
socket case(arg2):
if val==%arg2% or cont:
cont=True
socket
socket else:
socket
break
"""
that can be used like this:
"""
a=3
switch(a):
case(0):
print("Zero")
case(1):
print("Smaller than 2"):
break
else:
print ("greater than 1")
"""
so espy translate it in Python as:
"""
a=3
while True:
cont=False
if a==0 or cont:
cont=True
print ("Zero")
if a==1 or cont:
cont=True
print ("Smaller than 2")
break
print ("greater than 1")
break
"""
You can find and test ESPY in this page:
elp.chronocv.fr/?lng=en
Eric LE PAPE
15 Mar 2011 14:13:17
Well, switch is far more flexible than a dictionary. And for those of you out there that don't care, it would be useful to have dictionaries and switch statements.
26 Apr 2011 17:10:29
"repeat sections of code that you may have to in if statements"
That's what (nested) functions are for.
As for using a dictionary of lambdas ... that's stupid.
02 May 2011 17:05:19
The problem with switch is that it is not at all obvious how the comparisons should be structured, and exacty what ones should be done. Comparison in python CALLS A FUNCTION, and which comparisons get called therefore matters.
The if/elif/else approach calls them consecutively. The dictionary approach makes it obvious that I have no such expectation. And it makes it clear to whom I am handing over that choice.
Adding a switch statement would just encourage people to give up control and predictability, without making it obvious they are doing so.
In languages where comparison means something simpler, it can safely be used with less worries. In languages where it is flexible, and you want a switch statement, you end up with rules that are either complex or ambiguous.
02 May 2011 18:14:42
You know, maybe all that is really missing here is a multiline lambda-like construction, perhaps an anonymous version of def that returns the function defined instead of assiging it a name.
I.e.
x = def(blah):
<stuff>
would mean:
def x(blah):
<stuff>
Then we could easily define a public function something like
case( <expr>, {
<val>: def:
<stuff>
<val>: def:
<stuff>
}
)
And we could easily embed code-snippets into other calls without the constraints of the lambda syntax.
sum(x = range(1, 5),
def(x):
<complex function of x>
return value
)
Ending indentation after the def could be the equivalent of a comma (unless that would be the terminal tuple-construction comma). Then the inline and indented styles would not conflict too much.
This makes it clear that the selection is via dictionary lookup, and the syntax is not hopeless.
03 Jun 2011 15:05:17
This has most likely already been answered in a different way. But I thought I'd post it anyway in case someone somwhere runs into the same problem ^^.
I wanted to call a function with an argument without running it until called upon. This is how I did it. any ideas or comments on how to improve this is most welcome.
def command(myArgument):
print myArgument
dict = { 0 : lambda : command("argument")}
dict[0]()
08 Jun 2011 01:16:57
About GOTO: anyone who has written a finite sate machine knows why GOTO are useful (there is this kind of construct even in LISP!). Of course, one can do everything with only a Turing machine so it is easy to say Python does not need anything more. And, by the way, Python is not that fast to overlook efficient programming techniques. There is an interesting paper of "GOD" (I mean Donald Knuth) describing why GOTO are in some cases useful for good programming.