首页 > 解决方案 > 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?

标签: pythonimportrelative-import

解决方案


通常,当您将 python 模块作为主模块运行时,您不能使用相对导入,python filename.py但是有一个 hack 可以__package__用来实现这一点。请记住__package__python 如何解析相对导入:

__init__.py1-在您的根目录中创建一个名为的文件- 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命令行标志运行您的模块。


推荐阅读