How to import a module in Python with importlib.import_module

PythonImportModulePython Importlib

Python Problem Overview


I'm trying to use importlib.import_module in Python 2.7.2 and run into the strange error.

Consider the following dir structure:

a
|
+ - init.py
- b
|
+ - init.py
- c.py

a/b/__init__.py has the following code:

import importlib

mod = importlib.import_module("c")

(In real code "c"has a name.)

Trying to import a.b, yields the following error:

>>> import a.b
Traceback (most recent call last):
File "", line 1, in 
File "a/b/init.py", line 3, in 
mod = importlib.import_module("c")
File "/opt/Python-2.7.2/lib/python2.7/importlib/init.py", line 37, in   import_module
import(name)
ImportError: No module named c

What am I missing?

Thanks!

Python Solutions


Solution 1 - Python

For relative imports you have to:

  • a) use relative name

  • b) provide anchor explicitly

     importlib.import_module('.c', 'a.b')
    

Of course, you could also just do absolute import instead:

importlib.import_module('a.b.c')

Solution 2 - Python

I think it's better to use importlib.import_module('.c', __name__) since you don't need to know about a and b.

I'm also wondering that, if you have to use importlib.import_module('a.b.c'), why not just use import a.b.c?

Solution 3 - Python

And don't forget to create a __init__.py with each folder/subfolder (even if they are empty)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZaar HaiView Question on Stackoverflow
Solution 1 - PythonCat Plus PlusView Answer on Stackoverflow
Solution 2 - PythonGeraldView Answer on Stackoverflow
Solution 3 - PythonH.SechierView Answer on Stackoverflow