简体   繁体   English

Python从子模块导入子模块

[英]Python importing submodules from submodule

I have got a problem when using python imports. 使用python导入时出现问题。 I wrote a finished module, that itself uses several submodules (those are imported). 我写了一个完成的模块,它本身使用了几个子模块(已导入)。

eg 例如

module:
   main_class.py
   submodule1.py
   ....

Now I want to use this finished module by another supermodule, so the folder structure would change like this 现在我想由另一个超级模块使用此完成的模块,因此文件夹结构将像这样更改

supermodule:
    main_class_super.py     -- this class imports module.main_class
    module:
       main_class.py
       submodule1.py
       ....

However now all imports that are used in the code of main_class.py inside the module fail (I guess because the import now works in the namespace of main_class_super.py ) 但是,现在模块内部main_class.py的代码中使用的所有导入都会失败(我想是因为导入现在可以在main_class_super.py的命名空间中main_class_super.py

Any idea how to solve this problem without restructuring the entire sources? 有什么想法可以解决这个问题而无需重新组织整个资源吗?


The concrete error: 具体错误:

In my main_class.py I use the line: 在我的main_class.py ,使用以下行:

import submodule1

In my supermodule.py I use the line: 在我的supermodule.py ,使用以下行:

import module.main_class

When executing the superclass that imports module.main_class of course the import submodule1 line is executed as well, but fails as it can not find the module in the namespace of supermodule.py . 当然,在执行导入module.main_class的超类时, module.main_class执行import submodule1行,但会失败,因为它无法在supermodule.py的命名空间中找到该模块。

If you are on python 2 you should add from __future__ import absolute_import to your files (not needed on 3) so you can do the imports like Guido states in PEP 328 如果您使用的是python 2,则应将from __future__ import absolute_import添加到文件中(在3中不需要),以便可以执行PEP 328中的Guido状态之类的导入

According to this you should 根据这个你应该

  • Make sure all your package folders have a __init__.py in it to mark them as importable 确保所有包文件夹中都包含__init__.py ,以将其标记为可导入

  • In main_class.py: replace import submodule1 or import module.submodule1 with from . import submodule1 在main_class.py中:用from替换import submodule1import module.submodule1 module.submodule1 from . import submodule1 from . import submodule1

  • In main_class_super.py: replace import module.main_class with from .module import main_class 在main_class_super.py中:用from .module import main_class替换import module.main_class from .module import main_class

This way you don't have to care about any outer package structure. 这样,您不必关心任何外部包装结构。

The option to use absolute and explicit relative imports was added in Python 2.5. 在Python 2.5 中添加了使用绝对和显式相对导入的选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM