Zakery Alexander Fyke Zakery Alexander Fyke - 7 months ago 45
Python Question

Storing functions in a dictionary with different numbers of parameters

I've been toying with using a dictionary to replace a switch case in python. I have the following dictionary:

dispatcher = {"avg": data_filler.fill_missing_data_average,
"value": data_filler.fill_missing_data,
"drop": data_filler.drop_column}

Where fill_missing_data_average, fill_missing_data, and drop_column are all functions. I am then calling these functions in the following way:

for col in self.to_do_list:
self.pandas_dataset[col] = dispatcher[self.to_do_list[col]]()

Now, something should go in the () after the dispatcher call. But while fill_missing_data_average and drop_column both take a only a pandas dataframe as an argument, fill_missing_data takes both a pandas dataframe and a numerical value.

Is there a way to still use this method with functions that take a different number of parameters?


If you can modify the dispacher dict, you could wrap your your function referneces to lambdas. Its one way of doing this. Here is some example:

def fill_missing_data_average(a):

def fill_missing_data(a, b):
    print(a, b)

def drop_column(a):

dispatcher = {"avg": lambda a,_: fill_missing_data_average(a),
              "value": lambda a,b: fill_missing_data(a,b),
              "drop": lambda a,_: drop_column(a)}


This will print:

1 2