How to import a module given its name as string?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Switch On Looping
--
Chapters
00:00 Question
02:05 Accepted answer (Score 391)
02:42 Answer 2 (Score 377)
03:37 Answer 3 (Score 135)
04:31 Answer 4 (Score 38)
05:47 Thank you
--
Full question
https://stackoverflow.com/questions/3011...
Question links:
https://docs.python.org/3/library/functi...
Accepted answer links:
[Python 2]: https://docs.python.org/2/library/import...
[Python 3]: https://docs.python.org/3/library/import...
[Dive Into Python]: http://web.archive.org/web/2012031506111...
Answer 2 links:
[recommended]: https://docs.python.org/3/library/functi...
[importlib]: http://docs.python.org/3/library/importl...
Answer 3 links:
[imp]: http://docs.python.org/library/imp.html
Answer 4 links:
[importlib]: https://docs.python.org/3/library/import...
[from the documentation]: https://docs.python.org/3/library/import...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pythonimport
#avk47
ACCEPTED ANSWER
Score 414
With Python older than 2.7/3.1, that's pretty much how you do it.
For newer versions, see importlib.import_module for Python 2 and Python 3.
Or using __import__ you can import a list of modules by doing this:
>>> moduleNames = ['sys', 'os', 're', 'unittest']
>>> moduleNames
['sys', 'os', 're', 'unittest']
>>> modules = map(__import__, moduleNames)
Ripped straight from Dive Into Python.
ANSWER 2
Score 414
The recommended way for Python 2.7 and 3.1 and later is to use importlib module:
importlib.import_module(name, package=None)Import a module. The name argument specifies what module to import in absolute or relative terms (e.g. either
pkg.modor..mod). If the name is specified in relative terms, then the package argument must be set to the name of the package which is to act as the anchor for resolving the package name (e.g.import_module('..mod', 'pkg.subpkg')will importpkg.mod).
e.g.
my_module = importlib.import_module('os.path')
ANSWER 3
Score 137
Note: imp is deprecated since Python 3.4 in favor of importlib
As mentioned the imp module provides you loading functions:
imp.load_source(name, path)
imp.load_compiled(name, path)
I've used these before to perform something similar.
In my case I defined a specific class with defined methods that were required. Once I loaded the module I would check if the class was in the module, and then create an instance of that class, something like this:
import imp
import os
def load_from_file(filepath):
class_inst = None
expected_class = 'MyClass'
mod_name,file_ext = os.path.splitext(os.path.split(filepath)[-1])
if file_ext.lower() == '.py':
py_mod = imp.load_source(mod_name, filepath)
elif file_ext.lower() == '.pyc':
py_mod = imp.load_compiled(mod_name, filepath)
if hasattr(py_mod, expected_class):
class_inst = getattr(py_mod, expected_class)()
return class_inst
ANSWER 4
Score 18
Use the imp module, or the more direct __import__() function.