Python - Import module based on string then pass arguments
Question: Ive searched the web and this site and cant find an answer to this problem. Im
sure its right in front of me somewhere but cant find it.

I need to be able to import a module based on a string. Then execute a
function within that module while passing arguments.

I can import based on the string and then execute using eval() but I know this
is not the best way to handle this. I also cant seem to pass arguments that
way.

My current module that would be set based on a string is named TestAction.py
and lives in a folder called Tasks. This is the content of TestAction.py:

    
    
    def doSomething(var):
        print var
    

This is the code I am executing to import TestAction and execute.

    
    
    module = "Tasks.TestAction"
    import Tasks
    mymod = __import__(module)
    eval(module + ".doSomething()")
    

How can I make this code #1 not use `eval()` and #2 pass the var argument to
`doSomething()`?

Thanks in advance!


Answer: Is the function name also variable? If not, just use your imported module:

    
    
    mymod.doSomething('the var argument')
    

if it is, use `getattr`:

    
    
    fun = 'doSomething'
    getattr(mymod, fun)('the var argument')
    

