Patrick
Patrick

Reputation: 51

Dictionary to switch between methods with different arguments

A common workaround for the lack of a case/switch statement in python is the use of a dictionary. I am trying to use this to switch between methods as shown below, but the methods have different argument sets and it's unclear how I can accommodate that.

def method_A():
    pass
def method_B():
    pass
def method_C():
    pass
def method_D():
    pass
def my_function(arg = 1):
    switch = {
        1: method_A,
        2: method_B,
        3: method_C,
        4: method_D
    }
    option = switch.get(arg)
    return option()
my_function(input)  #input would be read from file or command line

If I understand correctly, the dictionary keys become associated with the different methods, so calling my_function subsequently calls the method which corresponds to the key I gave as input. But that leaves no opportunity to pass any arguments to those subsequent methods. I can use default values, but that really isn't the point. The alternative is nested if-else statements to choose, which doesn't have this problem but arguably less readable and less elegant.

Thanks in advance for your help.

Upvotes: 1

Views: 90

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51643

The trick is to pass *args, **kwargs into my_function and the **kwargs onto to your choosen function and evaluate it there.

def method_A(w):
    print(w.get("what"))  # uses the value of key "what"
def method_B(w):
    print(w.get("whatnot","Not provided")) # uses another keys value

def my_function(args,kwargs):
    arg = kwargs.get("arg",1)  # get the arg value or default to 1
    switch = {
        1: method_A,
        2: method_B,
    }
    option = switch.get(arg)
    return option(kwargs)

my_function(None, {"arg":1, "what":"hello"} ) # could provide 1 or 2 as 1st param
my_function(None, {"arg":2, "what":"hello"} ) 

Output:

hello
Not provided

See Use of *args and **kwargs for more on it.

Upvotes: 3

Related Questions