119

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
  • 9,152
  • 8
  • 37
  • 45

3 Answers3

137

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
  • 125,936
  • 27
  • 200
  • 224
  • This works for python 3.x, too. (OP asked about 2.7.) – JimB May 24 '22 at 15:45
  • 5
    could I rename it like we do with `import long_name as ln` ? – Abd-Elaziz Sharaf Jul 03 '22 at 05:58
  • 2
    you can, just assign a name to it like `abc = importlib.import_module('a.b.c')` – Jarartur Jul 12 '22 at 13:17
  • I am getting errors because I cannot find some utility functions that are not in a or b but are imported in c. How do I solve that? – Shreyas Vedpathak Jul 19 '22 at 10:24
  • what if `a` is already imported using `importlib` e.g `a = importlib.import_module("a")`, how can we then import b? `from a import b` does not work (`no module name 'a'`), if we don't want to import `a` again (which, for some reason, might have changed from the first import) – CutePoison Aug 21 '23 at 08:55
45

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
  • 888
  • 1
  • 7
  • 17
25

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

H.Sechier
  • 281
  • 3
  • 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