Mike Maazallahi
Mike Maazallahi

Reputation: 1289

Dynamically importing a package from inside another package

Here's the structure of the program:

├── app.py
├── apps
│   ├── __init__.py
│   ├── secure
│   │   ├── handler.py
│   │   └── __init__.py
└   └── test.py

I'm in app.py trying to import handler dynamically from inside app.secure as follows:

import importlib
a = importlib.import_module('handler', 'apps.secure')

by doing this I expect handler to be imported but I get the following error:

Traceback (most recent call last):
  File "/home/user/Projects/toolkit/app.py", line 5, in <module>
    a = importlib.import_module('handler', 'apps.sticker_to_sticker')
  File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked
ImportError: No module named 'handler'

after trying to use __import__ instead like __import__('apps.secure.handler') I noticed it actually imports the apps package. While from apps.secure import handler works fine. I need the import to be dynamic because the program needs to be able to load any package inside apps package.

Is there a way to dynamically import this module or I'll have to use exec?

Upvotes: 1

Views: 200

Answers (1)

TayTay
TayTay

Reputation: 7170

Try making the 'handler' import relative:

import importlib
a = importlib.import_module('.handler', 'apps.secure')

The documentation covers a similar example of relative import from within a submodule.

Upvotes: 2

Related Questions