处理 Python 中路径细微差别的项目结构

时间:2021-05-10 15:07:34

标签: python python-3.x flask project-structure

我正在开发一个 Python 项目,项目的当前结构如下所示:

myproject
__init.__py

contents
    - __init__.py
    - content1.py
    ...

configs
    - __init__.py
    - config.py
    ...
utils
    - __init__.py
    - helpers.py
    ..
app.py

现在如果我想从config.py目录中的configs访问函数到helpers.py,我需要在顶部的helpers.py中添加这两行:

import sys
sys.path.append("..")

同样,如果我想访问它们,我必须在每个目录的 py 文件中添加这些行。这显然不是正确的方式。有没有其他方法可以使 absoluterelative 导入更干净、更容易?任何关于它的解释都会非常有帮助

1 个答案:

答案 0 :(得分:0)

首先,有许多不同的方法可以实现您的目标。并非所有内容都清晰且易于维护(正如您使用 sys.path.append("..") 得出的结论)。

最佳做法 (IMO) 是导入 myproject/__init__.py 中其他地方需要的任何函数/类/等。

例如:

myproject/__init__.py

from configs import my_config_func

那么……

myproject/utils/helpers.py

from .. import my_config_func
相关问题