Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a module in Python with importlib.import_module

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!

like image 954
Zaar Hai Avatar asked May 20 '12 16:05

Zaar Hai


People also ask

What is import Importlib in Python?

The importlib package provides the implementation of the import statement in Python source code portable to any Python interpreter. This also provides an implementation which is easier to comprehend than one implemented in a programming language other than Python.

What is __ import __ in Python?

__import__() Parameters name - the name of the module you want to import. globals and locals - determines how to interpret name. fromlist - objects or submodules that should be imported by name. level - specifies whether to use absolute or relative imports.

How do I import a module into a string?

To import module from string variable with Python, we can use the importlib. imnport_module method. to call importlib. import_module with the module name string to import the module.


2 Answers

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') 
like image 164
Cat Plus Plus Avatar answered Sep 21 '22 17:09

Cat Plus Plus


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?

like image 25
Gerald Avatar answered Sep 25 '22 17:09

Gerald