python - relative import in python 3.9.5
问题描述
My folder structure is as follows
./fff
├── __init__.py
├── fg
│ ├── __init__.py
│ └── settings
│ ├── __init__.py
│ └── settings.py
└── obng
└── test.py
I want to import the settings.py inside fg/settings as a module into the test.py
I have added the line
from ..fg.settings import settings
But when I run it, it gives me the following error
Traceback (most recent call last): File "/mnt/d/Repos/fff/obng/test.py", line 1, in from ..fg.settings import settings ImportError: attempted relative import with no known parent package
This style of relative importing is supported as per https://docs.python.org/3/reference/import.html#package-relative-imports
What am I doing wrong here?
解决方案
通常,当您将 python 模块作为主模块运行时,您不能使用相对导入,python filename.py
但是有一个 hack 可以__package__
用来实现这一点。请记住__package__
python 如何解析相对导入:
__init__.py
1-在您的根目录中创建一个名为的文件- fff
. (我可以看到你有它,我提到完整性)
2-将此代码放在test.py
模块顶部:
if __name__ == '__main__' and not __package__:
import sys
sys.path.insert(0, <path to parent directory of root directory - fff>)
__package__ = 'fff.obng'
注意:sys.path
是 python 搜索模块以导入它们的地方。
3-现在将您的相对导入语句放在上面的代码之后(在 if 语句中,因为我们不想test.py
在导入时弄乱):
from ..fg.settings import settings
现在你可以打电话给你test.py
,它会毫无问题地运行。我不推荐使用这些技巧,但展示语言的灵活性并在某些情况下做你想做的事情是有益的。
其他好的解决方案:我认为绝对导入比这更容易和更干净。另外看看@Mr_and_Mrs_D's answer另一个好的解决方案是使用-m
命令行标志运行您的模块。
推荐阅读
- java - 如何使用 Mockito 模拟 @Value 类?
- flutter - 在 Firebase 上的表中更新表时出现问题
- mongodb - MongoDB如何找到一个确定命名的数组
- time-complexity - 具有时间复杂度的二维二分搜索
- javascript - 如何将图像上传到 MaterialTable 表?
- r - 在内置闪亮功能中设置文本样式
- css - 调整 Material UI Icon 高度的最佳实践
- python - 需要将一列加在一起并将平均值放在 Pandas 的列下方
- prediction - 在 config.json 中包含 allennlp 预测器参数
- google-apps-script - Google Apps 脚本在 Google Docs 的特定部分下提取文本