I have a situation where I have six possible situations that can relate to four different outcomes. Instead of using the extended if / else statement, I was wondering if it would be more pythonic to use a dictionary to call functions that I would call inside if / else as a replacement for the "switch" statement, as, for example, can be used in C # or php .
My switch statement depends on two values โโthat I use to create a tuple, which I, in turn, will use as a key for the dictionary, which will function as my โswitchโ. I get values โโfor a tuple from two other functions (database calls), so I have examples of the functions one () and zero ().
This is the code template that I am going to use that I came across while playing in a python shell:
def one(): #Simulated database value return 1 def zero(): return 0 def run(): #Shows the correct function ran print "RUN" return 1 def walk(): print "WALK" return 1 def main(): switch_dictionary = {} #These are the values that I will want to use to decide #which functions to use switch_dictionary[(0,0)] = run switch_dictionary[(1,1)] = walk #These are the tuples that I will build from the database zero_tuple = (zero(), zero()) one_tuple = (one(), one()) #These actually run the functions. In practice I will simply #have the one tuple which is dependent on the database information #to run the function that I defined before switch_dictionary[zero_tuple]() switch_dictionary[one_tuple]()
I don't have the actual code written or I would post it here, since I would like to know if this method is considered python best practice . I am still a python student at the university, and if this is a method that has a bad habit, then I would like to drop it now before I go out into the real world.
Please note that the result of executing the code above, as expected, is simply โRUNโ and โWALKโ.
change
For those who are interested in you, the corresponding code has turned out. It is used in the Google engine application. You should find the code significantly more accurate than my sample example. It works much better than my previous collapsed if / else tree.
def GetAssignedAgent(self): tPaypal = PaypalOrder() #Parent class for this function tAgents = [] Switch = {} #These are the different methods for the actions to take Switch[(0,0)] = tPaypal.AssignNoAgent Switch[(0,1)] = tPaypal.UseBackupAgents Switch[(0,2)] = tPaypal.UseBackupAgents Switch[(1,0)] = tPaypal.UseFullAgents Switch[(1,1)] = tPaypal.UseFullAndBackupAgents Switch[(1,2)] = tPaypal.UseFullAndBackupAgents Switch[(2,0)] = tPaypal.UseFullAgents Switch[(2,1)] = tPaypal.UseFullAgents Switch[(2,2)] = tPaypal.UseFullAgents #I'm only interested in the number up to 2, which is why #I can consider the Switch dictionary to be all options available. #The "state" is the current status of the customer agent system tCurrentState = (tPaypal.GetNumberofAvailableAgents(), tPaypal.GetNumberofBackupAgents()) tAgents = Switch[tCurrentState]()