How to import a module in Python with importlib.import_module
Asked Answered
P

3

123

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!

Parsons answered 20/5, 2012 at 16:12 Comment(0)
I
143

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')
Injudicious answered 20/5, 2012 at 16:17 Comment(5)
This works for python 3.x, too. (OP asked about 2.7.)Incorporable
could I rename it like we do with import long_name as ln ?Alternately
you can, just assign a name to it like abc = importlib.import_module('a.b.c')Etiology
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?Crepuscule
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)Atoll
T
47

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?

Truman answered 8/7, 2015 at 7:3 Comment(2)
It's useful when module name is a variable.Andreas
It's also useful when the module name is not a valid python identifier (e.g. has dashes in it).Weariful
M
27

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

Mizell answered 21/6, 2017 at 9:52 Comment(1)
Why though? I found this: https://mcmap.net/q/21646/-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."""Cash

© 2022 - 2024 — McMap. All rights reserved.