I want to write a code that takes file and class names, and operates over it. An example will explain it much more clearly than I possibly can:
I have a file test.py that goes as:
import pandas as pd
from preProcess import preProcess
from visualise import visualise
df=pd.read_csv('input.csv')
li1=["preProcess","visualise"]
li2=["minMax","pca"]
for i in range(len(li1)):
x = getattr(getattr(__import__(li1[i]),li1[i]), li2[i])
a=x(df)
# does some more stuff...
li1 contains name of the modules and li2 contains the name of the classes in the corresponding modules.
To make it a bit clearer, preProcess.py goes as:
class minMax():
def __init__(df):
# does something
and visualise.py goes as:
class pca():
def __init__(df):
# does something
The line x = getattr(getattr(__import__(li1[i]),li1[i]), li2[i]) gives me the classes minMax and pca.
Now the thing is that this code works perfectly fine if __init__ takes only one argument. But, what if it requires more than 1 arguments? For eg., pca could have been:
class pca():
def __init__(df,metaData):
# does something
What should I do in such a case? Any help would be appreciated.
If the question is not clear, please drop a comment. I would provide a more detailed explanation then. Thanks...
1 Answer 1
perhaps you should utilize the spread operator. maybe this snippet helps:
class X:
def __init__(self, a, b):
self.a = a
self.b = b
args = [2, 'hellow']
x = X(*args)
EDIT: this is just an outline of the general approach. for a more comprehensive overview of how this approach is applicable to this specific problem, please check the discussion on this answer.
7 Comments
args in my implementation. There can be about 100 such function, that too overloaded. It won't be feasible for me... (PS: I didn't downvote)f(a,b=None). To make a list for args, I'll need to check if the user passes b or not. What you are saying is 100% correct, but I cannot use if-else statements in my code due to scalability issue.test.py to have the line a=x(df,dict) and all functions f to f(df,*args). Then, I'm using args in the functions I need (and it works as I want it to). Thanks...