How to Import a Module Given Its Name as String

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 like importlib.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



Leave a reply



Submit