python - 通过在__init__.py 中导入子包来跳过导入路径中的目录名

标签 python python-3.x

我对 __init__.py 中的导入动态感到困惑。 假设我有这样的结构:

package
├── __init__.py
└── subpackage
    ├── __init__.py
    └── dostuff.py

我想在 dostuff.py 中导入内容。我可以这样做:from package.subpackage.dostuff import thefunction,但我想删除 import 语句中的 subpackage 级别,所以它看起来像这样:

from package.dostuff import thefunction

我试着把它放在 package/__init__.py 中:

from .subpackage import dostuff

我不明白的是:

# doing this works:
from package import dostuff
dostuff.thefunction()

# but this doesn't work:
from package.dostuff import thefunction
# ModuleNotFoundError: No module named 'package.dostuff'

为什么会这样,我怎样才能使 from package.dostuff import thefunction 工作?

最佳答案

我认为实现您的意图的唯一方法是实际创建一个 package/dostuff.py 模块并将您需要的所有内容导入其中作为 from .subpackage.dostuff import thefunction

重点是,当您在 package/__init__.py 中使用 from .subpackage import dostuff 时,您不会重命名原始模块。

更明确地说,这里是一个使用导入和 package/dostuff.py 文件的例子:

# We import the dostuff link from package
>>> from package import dostuff
>>> dostuff
<module 'package.subpackage.dostuff' from '/tmp/test/package/subpackage/dostuff.py'>

# We use our custom package.dostuff
>>> from package.dostuff import thefunction
>>> package.dostuff
<module 'package.dostuff' from '/tmp/test/package/dostuff.py'>
>>> from package import dostuff
>>> dostuff
<module 'package.dostuff' from '/tmp/test/package/dostuff.py'>

# The loaded function is the same
>>> dostuff.thefunction
<function thefunction at 0x7f95403d2730>
>>> package.dostuff.thefunction
<function thefunction at 0x7f95403d2730>

更清晰的表达方式是:

from X import Y 仅在 X 是实际模块路径时有效。 Y 相反,可以是此模块中导入的任何项目。

这也适用于在其 __init__.py 中声明任何内容的包。在这里,您在 package 中声明了模块 package.subpackage.dostuff,因此您可以导入并使用它。

但是如果您尝试使用该模块进行直接导入,它必须存在于文件系统中

资源:

我希望这能让它更清晰

关于python - 通过在__init__.py 中导入子包来跳过导入路径中的目录名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55748845/

相关文章:

python - 如何在 Mac 上将 openCV 安装到 Enthought python 发行版中

python - 为什么相等在 Python 中似乎不是对称关系?

python - Flask APP - ValueError : signal only works in main thread

python-3.x - 空白字符串的正则表达式

python - postgres 触发通知 - 什么更好 : before or after

python - 为什么扁平化列表中的项目为空白

python - 在另一个线程中与另一个 TCP 服务器一起使用 Flask

string - 在python 3中从文件末尾查找

python - Heroku 上的交互式 Ipython 笔记本

python-3.x - Python,子图 pandas 数据框的最有效方法