0

I have a peculiar problem at hand. There is an excel workbook and I am able to extract the sheet names as follows:

import xlrd
xls = xlrd.open_workbook(r'<path_to_your_excel_file>', on_demand=True)
sheet_names = [xls.sheet_names()]

I also have a set of funtions defined for each sheet. And the name of the function is same as the names of the sheets (abc, pqr, def,lmn) and a suffix of worksheet along with it. The number of input parameters are identical for each of these functions. i.e.

def abc_worksheet(arg1, arg2):
    # returns abc_cleaned_csv
    pass
def pqr_worksheet(arg1, arg2):
    # returns pqr_cleaned_csv
    pass
def def_worksheet(arg1, arg2):
    # returns def_cleaned_csv
    pass
def lmn_worksheet(arg1, arg2):
    # returns lmn_cleaned_csv
    pass

However it is unknown that in each workbook how many of these sheets would be present, i.e. today's workbook has worksheets (abc, pqr) and yesterday's workbook had worksheets (pqr, def, lmn).

What is the most pythonic way to call the processing functions according to the worksheets for any workbook?

I tried function dictionary mapping. But I am not able to call the fucntions dynamically and I feel it is not optimised.

func_dict = {'abc' : abc_worksheet
            ,'pqr' : pqr_worksheet
            ,'def' : def_worksheet
            ,'lmn' : lmn_worksheet}

for ele in sheet_names:
    func_dict[ele](arg1, arg2)

Please suggest.

  • 1
    1. This approach is very pythonic and there is nothing unoptimized about it. 2. What do you mean by "I am not able to call the fucntions variably"? – Physmatik Aug 20 '23 at 18:17
  • "I am not able to call the fucntions variably and I feel it is not optimised" - Just as Physmatik, I have trouble understanding what do you mean by both of those statements – dankal444 Aug 21 '23 at 15:37
  • What I meant to ask was that adding a function dictionary to the main Python code hinders scalability. @Physmatik I have written the worksheet functions in a different file and I am importing the file as a package in the main function. If I have to add 5 more functions after a month, I will have to alter the main code (function dictionary) which is not a best practice. So I wanted to understand how to do it dynamically. – damd biker Aug 24 '23 at 03:48
  • thanks all. I have the solution here: https://stackoverflow.com/questions/4246000/how-to-call-python-functions-dynamically – damd biker Aug 25 '23 at 11:45

0 Answers0