Python - import a module based on a string, then pass arguments

Ive searched the website and this website and could not find an answer to this problem. I am sure that he is right in front of me, but I cannot find him.

I need to be able to import a module based on a string. Then execute the function inside this module when passing the 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 cannot pass arguments this way.

My current module, which will be installed based on the string, is called TestAction.py and lives in the Tasks folder. This is the contents of TestAction.py:

def doSomething(var): print var 

This is the code that I execute 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!

+6
source share
5 answers

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

 mymod.doSomething('the var argument') 

if so, use getattr :

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

Thank you all for your help. it looks like importlib combined with getattr was what I needed. For future reference, here is the code that works for me.

 module = "FarmTasks.TestAction" mymod = importlib.import_module(module) ds = getattr(mymod, "doSomething") ds("stuff") 
+2
source

According to the documentation

it is better to use importlib.import_module () to programmatically import the module.

With this, you can get your module as follows:

 import importlib TestAction = importlib.import_module("TestAction", package="Tasks") 

After that, you can simply call the functions normally or by name:

 TestAction.some_known_function(arg1, arg2) getattr(TestAction, "some_other_function_name")(arg1, arg2) 

I hope this is the answer to your question, do not hesitate to clarify if you are still not noticing something.

+1
source

If you are using Python 2.7 or 3.1+, the easiest way is to use the importlib module in conjunction with getattr . Then your code will look like this:

 import importlib module = "Tasks.TestAction" mymod = importlib.import_module(module) myfunc = getattr(mymod, "doSomething") myfunc() 
0
source

I recently wrote a simple function that imports a given function, it works for me:

 def import_function(name): """Import a function by name: module.function or module.submodule.function, etc. Return the function object.""" mod, f = name.rsplit('.', 1) return getattr(__import__(mod, fromlist=[f]), f) 

You can use it like:

 f = import_function('Tasks.TestAction.doSometing') f() 

or simply

 import_function('Tasks.TestAction.doSometing')() 
0
source

Source: https://habr.com/ru/post/943646/


All Articles