I have functions that i want to run with differents parameters
Here is the directory structure:
App/
├─ main.py
└─ fcts1.py
└─ fcts2.py
└─ File1.csv
└─ File2.csv
└─ Files/
└─B.xlsx
└─A.xlsx
└─C.xlsx
Sometimes i want to run those functions with df = pd.read_excel(file1)
and fct1()
from the file fcts1.py and sometimes with
df = pd.read_excel(file2)
and fct1()
from the file fcts2.py
Exp 1:
file1 = "file1.csv"
from fcts1 import fct1
def A_fct(fileA):
df = pd.read_excel(file1)
dfA = pd.read_excel(fileA)
fct1()
def B_fct(fileB):
df = pd.read_excel(file1)
dfB = pd.read_excel(fileB)
fct1()
def C_fct(fileC):
df = pd.read_excel(file1)
dfC = pd.read_excel(fileC)
fct1()
Exp 2 :
file2 = "file2.csv"
from fcts2 import fct1
def A_fct(fileA):
df = pd.read_excel(file2)
dfA = pd.read_excel(fileA)
fct1()
def B_fct(fileB):
df = pd.read_excel(file2)
dfB = pd.read_excel(fileB)
fct1()
def C_fct(fileC):
df = pd.read_excel(file2)
dfC = pd.read_excel(fileC)
fct1()
NB: fct1() in fcts1.py is not the same as fct1() in fcts2.py How can i dot it please?
CodePudding user response:
I don't know if I understand your question but maybe using alias for your functions???
from fcts1 import fct1 as f1
from fcts2 import fct1 as f2
CodePudding user response:
You can replace these 6 functions with one:
def fct(file_number, file_letter, function):
# Key idea: you can pass functions as arguments
df = pd.read_excel(file_number)
dfA = pd.read_excel(file_letter)
function()
This can be called like this:
import fcts1, fcts2
fct("file1.csv", whatever_file, fcts1.fct1)
fct("file2.csv", whatever_file, fcts2.fct1)
CodePudding user response:
Consider creating a settings/parameter dictionary at the top of main.py
, and then passing it to your main function. Essentially this means that you only need to modify this dictionary, not the code itself, in order to re-run your analysis with different files or functions.
Example:
from fcts1 import fct1 as function1
from fcts2 import fct1 as function2
SETTINGS = {
'file1': "file1.csv",
'file2': "file2.csv",
'function': function1,
}
def main(file1, file2, function):
df1 = pd.read_excel(file1)
df2 = pd.read_excel(file2)
function()
if __name__ == '__main__':
main(**SETTINGS)
Two things to note:
- I've aliased the
fct1
s tofunction1
andfunction2
in order to be able to differentiate them. In reality, your code would benefit a lot from better variable names. - We're using a starred expression in
main(**SETTINGS)
, which means that the arguments in theSETTINGS
dictionary are properly delivered to themain
function as long as the dictionary's key names match the function's parameter names.