简体   繁体   English

Python子软件包不可用于导入

[英]Python Subpackages not available for import

I'm working from the basis of this previously posted problem: module importing itself 我正在根据之前发布的问题进行工作: 模块本身导入

Essentially, that problem is solved, but in the "modulename.py" file, there is a class defined, with an init function, and a ui function. 本质上,该问题已解决,但是在“ modulename.py”文件中,定义了一个带有init函数和ui函数的类。 Inside the class, any line of the form: 在类内,该行的任何形式:

import submodule

Will function just fine. 将正常工作。 However.. 然而..

import submodule.subsubmodule

or 要么

import subsubmodule

Will produce an ImportError. 会产生一个ImportError。

All submodules and subsubmodules have an 所有子模块和子子模块都有一个

__init__.py

file. 文件。

This often happens if you have multiple modules with the same name inside a package. 如果包中有多个具有相同名称的模块,则经常会发生这种情况。

For example, consider: 例如,考虑:

mypkg/
  __init__.py
  toplevel.py
  mypkg.py

If the toplevel.py file calls import mypkg.mypkg , it will actually be importing the mypkg.py file and not the package. 如果toplevel.py文件调用import mypkg.mypkg ,它将实际上是在导入mypkg.py文件而不是软件包。

You can solve this by including from __future__ import absolute_import as the first line in toplevel.py , which will force it to import the top-level package. 您可以通过将from __future__ import absolute_import作为toplevel.py的第一行包括在内来解决此问题,这将强制其导入顶级包。

Alternatively, you can use from . import mypkg 或者,您可以使用from . import mypkg from . import mypkg in toplevel.py , which will explicitly import the mypkg.py file. toplevel.py from . import mypkg ,它将显式导入mypkg.py文件。

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

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