Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Import module based on string then pass arguments

Tags:

python

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!

like image 677
user2321177 Avatar asked Apr 25 '13 19:04

user2321177


People also ask

How do you pass parameters to a Python module?

In the module you can check dir() or similar, to see if the variable is defined. Show activity on this post. There is no such way to pass parameters to the module, however you can revamp your code a bit and import the parameters from a module as global parameters.

How do I import a module into a string?

Use importlib to programmatically import modules The importlib provides a simple import_module function that accepts a string name with dot separators. It works just like a normal import except it uses a string to store the name. On import, the file is executed and the module object is returned.

What is __ import __ in Python?

__import__() Parameters name - the name of the module you want to import. globals and locals - determines how to interpret name. fromlist - objects or submodules that should be imported by name. level - specifies whether to use absolute or relative imports.


2 Answers

Thanks everyone for the help. it looks like importlib combined with getattr was what I needed. For future reference here is the exact code that is working for me.

module = "FarmTasks.TestAction"
mymod = importlib.import_module(module)

ds = getattr(mymod, "doSomething")
ds("stuff")
like image 75
user2321177 Avatar answered Oct 11 '22 14:10

user2321177


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')
like image 37
Pavel Anossov Avatar answered Oct 11 '22 13:10

Pavel Anossov