105

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!

Zaar Hai
  • 8,067
  • 8
  • 33
  • 44

3 Answers3

126

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')
Cat Plus Plus
  • 119,938
  • 26
  • 191
  • 218
41

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?

Gerald
  • 849
  • 1
  • 7
  • 17
22

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

H.Sechier
  • 251
  • 2
  • 7
  • 3
    Why though? I found this: https://stackoverflow.com/questions/448271/what-is-init-py-for#448279 with the comment by @TwoBItAlchemist being most useful I think """Python searches a list of directories to resolve names in, e.g., import statements. Because these can be any directory, and arbitrary ones can be added by the end user, the developers have to worry about directories that happen to share a name with a valid Python module, such as 'string' in the docs example. To alleviate this, it ignores directories which do not contain a file named _ _ init _ _.py (no spaces), even if it is blank.""" – Goblinhack May 29 '20 at 17:55