gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:48:40 26 4
gpt4 key购买 nike

我对 __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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com