import module from string variable
The __import__
function can be a bit hard to understand.
If you change
i = __import__('matplotlib.text')
to
i = __import__('matplotlib.text', fromlist=[''])
then i
will refer to matplotlib.text
.
In Python 2.7 and Python 3.1 or later, you can use importlib
:
import importlib
i = importlib.import_module("matplotlib.text")
Some notes
If you're trying to import something from a sub-folder e.g.
./feature/email.py
, the code will look likeimportlib.import_module("feature.email")
You can't import anything if there is no
__init__.py
in the folder with file you are trying to import
How to import a module given its name as string?
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.
You can use exec
if you want to as well.
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.
importing a module when the module name is in a variable
You want the built in __import__
function
new_module = __import__(modulename)
How to load a module from code in a string?
Here is how to import a string as a module (Python 2.x):
import sys,imp
my_code = 'a = 5'
mymodule = imp.new_module('mymodule')
exec my_code in mymodule.__dict__
In Python 3, exec is a function, so this should work:
import sys,imp
my_code = 'a = 5'
mymodule = imp.new_module('mymodule')
exec(my_code, mymodule.__dict__)
Now access the module attributes (and functions, classes etc) as:
print(mymodule.a)
>>> 5
To ignore any next attempt to import, add the module to sys
:
sys.modules['mymodule'] = mymodule
import specific module from the class by different name as string variable
You can use getattr()
For example:
getattr(timm.models, target_network_root)
=> timm.models.resnet
How to get reference to module by string name and call its method by string name?
To get the module, you can use globals
. To get the function, use getattr
:
getattr(globals()[module_name], function_name)
Importing a module just binds the module object to a name in whatever namespace you import it in. In the usual case where you import at the top level of the module, this means it creates a global variable.
Import a class with a string
In Python 2.7 and Python 3.1 or later, you can use importlib:
import importlib
i = importlib.import_module("module_name")
If you want to access the class, you can use getattr
:
import importlib
module = importlib.import_module("module_name")
class_ = getattr(module, class_name)
instance = class_()
Related Topics
Why Are Multiple Instances of Tk Discouraged
How to Make a Dictionary from Separate Lists of Keys and Values
Pygame Mouse Clicking Detection
List Comprehension Without [ ] in Python
What Happens When Using Mutual or Circular (Cyclic) Imports in Python
How to Type Hint a Method With the Type of the Enclosing Class
Error "Microsoft Visual C++ 14.0 Is Required (Unable to Find Vcvarsall.Bat)"
Remap Values in Pandas Column With a Dict, Preserve Nans
How to Split a String into a List
Configure Flask Dev Server to Be Visible Across the Network
How to Do Relative Imports in Python
Why Does "Pip Install" Inside Python Raise a Syntaxerror
How to Make a Python Script Standalone Executable to Run Without Any Dependency
How to Convert Webpage into Pdf by Using Python
Flask Raises Templatenotfound Error Even Though Template File Exists
Force Python to Use an Older Version of Module (Than What I Have Installed Now)