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
python python-3.x python-import


source to share


No one has answered this question yet

Check out similar questions:

3602
Does Python have a substring method "contains"?
2818
Finding the index of an element by specifying the list that contains it in Python
1130
Importing files from different folders
985
How do I import a module with a full path?
706
Import module from relative path
669
How to fix "Attempting relative import in non-package" even with __init__.py
563
Relative imports in Python 3
516
Relative imports per billion
494
How do I do relative imports in Python?
0
Error importing Python 3 module from another folder



All Articles
Loading...
X
Show
Funny
Dev
Pics