Reputation: 1053
I want to dynamically import functions from a module that will mimic the import
keyword so all modules in the dotted string will be imported.
For example, I want to use a function I can do
import module1.module2.module3
module1.module2.module3.func()
When I import module1.module2.module3
dynamically it does not work
importlib.import_module("module1.module2.module3")
module1.module2.module3.func()
I'm getting NameError: name 'module1' is not defined
To make it work I need to break the dotted string and import all parts:
importlib.import_module("module1")
importlib.import_module("module1.module2")
importlib.import_module("module1.module2.module3")
module1.module2.module3.func()
Is there a way to get the import_module
to import all modules in the string?
(I tried __import__()
with the same result)
What I want to do is use eval
to run the function (I know eval
is not recommended but this is not the question)
globals_ = {}
globals_["module1"] = importlib.import_module("module1")
eval("module1.module2.module3.func()", globals_)
AttributeError: 'module' object has no attribute 'module2'
Upvotes: 1
Views: 410
Reputation: 1053
I was able to achieve this by importing all the modules in the path to a "globals" and pass it to the eval
import itertools
import importlib
globals_ = {}
modules = itertools.accumulate([module] for module in "module1.module2.module3")
for module in modules:
globals_[module] = importlib.import_module(".".join(module))
eval("module1.module2.module3.func()", globals_)
not sure if it is possible without importing all modules manually.
Upvotes: 1
Reputation: 1312
You need to bind it to a variable
module1 = importlib.import_module("module1")
Have a look at the docs for the semantics: python docs
Upvotes: 1