python - 在导入父包后调用模块

标签 python python-import

我一直在努力弄清楚如何在导入父包后调用模块。

目录结构如下:

.
├── main
│   └── pkg
│       └── file.py
└── another_main

注意:所有包都包含__init__.py 文件,并且设置了所有必要的路径变量。我没有在这里展示它,因为这只是一个虚拟结构。

如果我这样做:

from main import pkg
pkg.file

这不起作用并抛出 AttributeError: module 'pkg' has no attribute 'file'

但如果我首先这样做:

from main.pkg import file

之后我可以做:

from main import pkg
pkg.file  # --> Now this doesn't throw AttributeError

有没有一种方法可以像 pkg.file 一样调用 file 而无需执行 from main.pkg import file

P.S.:我想在我的脚本中使用 pkg.file 以便将来我可以记忆起我从 调用了 file >pkg 而不是 some_other_pkg

最佳答案

main/pkg__init__.py 中,您必须导入 file:

# pkg/__init__.py

import pkg.file

# EDIT: if the import above does not work, use this instead

from . import file

关于python - 在导入父包后调用模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68141238/

相关文章:

python - StringIO 和 BytesIO 有什么区别?

python - 在mongoengine中查询列表;包含与在

python - 除非 root 用户,否则无法导入 python 模块

python - 在 Python 中,为什么我不能执行 : import A; A. B.C.foo()

python - 在同一个 Python 包中加载模块

python - 工作电脑python包安装失败

python - 如何更新基于其他 Pandas 数据框的系列

python - 在 Linux 中实时监控鼠标坐标

Python:导入 "import file"

c# - IronPython 无法导入操作系统 : ImportException: "not a Zipfile"