简体   繁体   中英

How to import module by variable name and how to name said module

So I want to import a python script depending on a variable name. Say I pass this function the module path, I'd like it to import that module from the path I passed and give it a name. Example:

import some_module as sm
#Would import some_module

What I want is something like this

module_to_import = some_other_module
import module_to_import as mti
#Would import some_other_module

Sorry if this doesn't make much sense, was quite difficult to put into words.

Thanks.

with importlib.import_module you could do this:

from importlib import import_module
module_name = 'some_module'

mti = import_module(module_name)

meaning you could import the module from a string. in your case you might get that name from your other module using

module_name = some_other_module.__name__

What you probably are looking for is ability to dynamically import modules

module = __import__(module_name)
my_class = getattr(module, class_name)
instance = my_class()

You can read more about this and alternative solutions at this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM