【问题标题】:Project structure to deal with Path nuances in Python在 Python 中处理路径细微差别的项目结构
【发布时间】:2023-03-26 01:00:01
【问题描述】:

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

myproject
__init.__py

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

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

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

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

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

【问题讨论】:

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


    【解决方案1】:

    首先,有许多不同的方法可以实现您想要做的事情。并非所有这些都清晰且易于维护(正如您使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-12
      • 2011-04-26
      • 1970-01-01
      • 2015-03-19
      • 2020-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多