ChatGPT解决这个技术问题 Extra ChatGPT

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!


C
Cat Plus Plus

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')

This works for python 3.x, too. (OP asked about 2.7.)
could I rename it like we do with import long_name as ln ?
you can, just assign a name to it like abc = importlib.import_module('a.b.c')
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?
G
Gerald

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?


It's useful when module name is a variable.
It's also useful when the module name is not a valid python identifier (e.g. has dashes in it).
H
H.Sechier

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


Why though? I found this: 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."""