Import Module from String Variable

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

Import a module from string variable

There are limitations in the import syntax that make it difficult to do if not impossible without using external libraries.

The closest I could get is by using the Dynamic Import syntax. An example follows:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<script>
var moduleData = "export function hello() { alert('hello'); };";
var b64moduleData = "data:text/javascript;base64," + btoa(moduleData);

</script>
<script type="module">

async function doimport() {
const module = await import(b64moduleData);
module.hello();
}

doimport();

</script>

</body>
</html>

You will however notice that this has some limitations on the way the import code is constructed, which may not precisely match what you need.
The simplest solution is probably to send the code of the module on the server for it to generate a temporary script to be then imported using a more conventional syntax.

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.

how to import module in python using string

you can use python default function __import__ to import modules.

mod = __import__(module)

but path of this module need to be appended in sys.path

sys.path.insert(0, <path of module>)

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_()

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

How do I access a module using a string variable as a location?

If you need to dynamically import, take look at importlib.import_module consider following simple example

import importlib
modulename = "html"
submodulename = "entities"
what = "html5"
module = importlib.import_module(modulename + "." + submodulename)
thing = getattr(module,what)
print(thing["gt;"]) # >

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


Related Topics



Leave a reply



Submit