Reputation: 13
I have implemented a second switch case statement into my code but for some reason one works and the other doesn't.
The broken one in question is this:
def graph_add_depend(caseSelected, graph, data):
switcher = {
1: graph.addFullNC(data[1], data[0]),
2: graph.addFullNC(data[0], data[1]),
0: graph.addFullNC2(data[0], data[1])
}.get(caseSelected, print("Something went wrong: GAD 44"))
I am calling it with:
graph_add_depend(is_added, graph, temp)
When i execude the code it wont go to the correct case but will execute every one of them: aka 1 then 2 then 0
Is there anyway to fix this. I cant by the love of god find the problem. The most frustrating thing to me is that by my eye the switch statement that works and this broken one are virtualy the same...
Upvotes: 0
Views: 2493
Reputation: 42133
you can simulate a switch statement using this function definition:
def switch(v): yield lambda *c: v in c
Using it will give you code that a lot more legible:
for case in switch(caseSelected):
if case(1):
graph.addFullNC(data[1], data[0])
break
if case(2):
graph.addFullNC(data[0], data[1])
break
if case(0):
graph.addFullNC2(data[0], data[1])
break
else:
print("Something went wrong: GAD 44"))
you can also use it with if/elif/else patterns without the breaks:
for case in switch(caseSelected):
if case(1):
graph.addFullNC(data[1], data[0])
elif case(2):
graph.addFullNC(data[0], data[1])
elif case(0):
graph.addFullNC2(data[0], data[1])
else:
print("Something went wrong: GAD 44"))
Upvotes: 0
Reputation: 71424
If you don't want the function to be called unless it matches the case, don't call it when you build the dictionary. Wrapping each case in a lambda
is a pretty easy way to delay that evaluation:
def graph_add_depend(caseSelected, graph, data):
return {
1: lambda: graph.addFullNC(data[1], data[0]),
2: lambda: graph.addFullNC(data[0], data[1]),
0: lambda: graph.addFullNC2(data[0], data[1])
}[caseSelected]()
Note that this will automatically raise a KeyError
if caseSelected
is not a valid option; raising an exception is generally a better option than printing a message and returning nothing.
Upvotes: 2