Dynamically importing modules containing relative imports

Here's the setting:

 program [root]
  ├─ main.py
  ├─ utils
  |   |
  |   └─ util1.py
  └─ plugins
      |
      └─ plugin1.py

      

Now I want to dynamically load all plugins with pkgutil.iter_modules()

, which works great. Until I put from ..utils import util1

in plugin1. Then I get

ValueError: attempted relative import beyond top-level package

      

I've tried two things. First, I used importer.find_module().load_module()

like this:

for importer, module_name, ispkg in pkgutil.iter_modules(plugins.__path__):
    importer.find_module(module_name).load_module(module_name)

      

and since it __package__

was empty in plugin1 I also tried importlib.import_module()

like this:

module = importlib.import_module(package + "." + module_name, package=package)

      

from package

since "plugins"

and adding each line under plugins

a string split.

Any ideas how I could make this work?

+3


source to share





All Articles