1

Say I want to parse a text file that has lines:

sampleMethod 
sampleParameter
sampleParameter2

where sampleMethod is a string of a method and sample parameters can be any type values.

I know I can use getattr to dynamically call something givn we know the module and method name:

output = getattr(componentName, sampleMethod)(sampleParameter)

but how can I do this if there are multiple parameters we discover dynamically?

So for example if the text file has:

sampleMethod 
sampleParameter
sampleParameter2
sampleParameter3

how can we do someting like this dynamically?

  output = getattr(componentName, sampleMethod)(sampleParameter, sampleParameter2, sampleParameter3)

3 Answers 3

1

You could unpack your argument lists (the special *) :

# you could dynamically build the list 
parameterList = [sampleParameter, sampleParameter2, sampleParameter3]

# then pass as parameter
output = getattr(componentName, sampleMethod)(*parameterList)

Note that you do not have to use arbitrary argument lists if you are sure that parameterList will not be bigger than the number of parameters of sampleMethod (otherwise you can get an runtime error).

If you are not sure, you can still just slice the list first or use arbitrary argument lists.

Sign up to request clarification or add additional context in comments.

Comments

0

You could use * in the attribute of the function definition. It will treat all argument which are not matched into a tuple. For example:

def print_for(*args):
    print args

print_for(1,2,3)
print_for(1,2,3,4)

Comments

0
from importlib.machinery import SourceFileLoader

inputParams = ["1st_param", "2nd_param", ....]
module=SourceFileLoader("module_name","absolute/path/to/pyfile").load_module()
method = getattr(module, "functionname")
result = method(*inputParams)
print(result)

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.