简体   繁体   中英

Python dynamic import with submodules

I want to dynamically import functions from a module that will mimic the import keyword so all modules in the dotted string will be imported.

For example, I want to use a function I can do

import module1.module2.module3
module1.module2.module3.func()

When I import module1.module2.module3 dynamically it does not work

importlib.import_module("module1.module2.module3")
module1.module2.module3.func()

I'm getting NameError: name 'module1' is not defined

To make it work I need to break the dotted string and import all parts:

importlib.import_module("module1")
importlib.import_module("module1.module2")
importlib.import_module("module1.module2.module3")
module1.module2.module3.func()

Is there a way to get the import_module to import all modules in the string? (I tried __import__() with the same result)

What I want to do is use eval to run the function (I know eval is not recommended but this is not the question)

globals_ = {}
globals_["module1"] = importlib.import_module("module1")
eval("module1.module2.module3.func()", globals_)

AttributeError: 'module' object has no attribute 'module2'

You need to bind it to a variable

module1 = importlib.import_module("module1")

Have a look at the docs for the semantics: python docs

I was able to achieve this by importing all the modules in the path to a "globals" and pass it to the eval

import itertools
import importlib

globals_ = {}
modules = itertools.accumulate([module] for module in "module1.module2.module3")
for module in modules:
    globals_[module] = importlib.import_module(".".join(module))

eval("module1.module2.module3.func()", globals_)

not sure if it is possible without importing all modules manually.

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