How to import a module in Python with importlib.import_module

前端 未结 3 1666
臣服心动
臣服心动 2020-11-28 08:19

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
    |
    + - __ini         


        
相关标签:
3条回答
  • 2020-11-28 08:49

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

    0 讨论(0)
  • 2020-11-28 08:50

    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')
    
    0 讨论(0)
  • 2020-11-28 09:01

    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?

    0 讨论(0)
提交回复
热议问题