Import File Using String As Name
Possible Duplicate: Dynamic module import in Python I intend to make a suite of files at some point soon, and the best way to organize it is to have a list, that list will be at
Solution 1:
Not sure if I understood everything correctly, but you can import a module dynamically using __import__
:
mod = __import__(testName)
mod.HelloWorld()
Edit: I wasn't aware that the use of __import__
was discouraged by the python docs for user code: __import__ documentation (as noted by Bakuriu)
This should also work and would be considered better style:
importimportlibmod= importlib.import_module(testName)
mod.HelloWorld()
Solution 2:
- Never, ever, ever mess with
sys.modules
directly if you don't know exactly what you are doing. - There are a lot of ways to do what you want:
- The build-in
__import__
function - Using
imp.load_module
- Using
importlib.import_module
- The build-in
I'd avoid using __import__
directly, and go for importlib.import_module
(which is also suggested at the end of the documentation of __import__
).
Solution 3:
Add the path where module resides to sys.path. Import the module using __import__ function which accepts a string variable as module name.
import sys
sys.path.insert(0, mypath) # mypath = path of module to be imported
imported_module = __import__("string_module_name") # __import__ accepts string
imported_module.myfunction() # All symbols in mymodule are now available normally
Post a Comment for "Import File Using String As Name"