Ankit Kumar
Ankit Kumar

Reputation: 1281

Passing variable arguments : python

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...

Upvotes: 0

Views: 59

Answers (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.

Upvotes: 1

Related Questions