【问题标题】:Imports with complex folder hierarchy具有复杂文件夹层次结构的导入
【发布时间】:2017-08-11 22:16:04
【问题描述】:

嘿,我正在开发一个项目,该项目具有一组分层模块,其文件夹结构设置如下:

module_name/
    __init__.py
    constants.py
    utils.py
    class_that_all_submodules_need_access_to.py

    sub_module_a/
        __init__.py
        sub_module_a_class_a.py
        sub_module_a_class_b.py
        useful_for_sub_module_a/
             __init__.py
             useful_class_a.py
             useful_class_b.py

    sub_module_b/
        __init__.py
        sub_module_b_class_a.py
        sub_module_b_class_b.py

等等等等……

问题是,我不知道如何在 init.py 中设置导入,以便可以从 sub_module_a/useful_for_sub_module_a/useful_class_a.py 访问 class_that_all_submodules_need_access_to.py。

我已尝试在 Google/StackOverflow 上查找此内容,但我已经力不从心了。奇怪的是,PyCharm 的路径设置方式使我在 PyCharm 中处理项目时不会遇到此错误,而只会在其他环境中遇到此错误。

所以这是我想出的一个特别不雅的解决方案。我的 sub_module_a/useful_for_sub_module_a/init.py 看起来像:

import sys
import os

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))

import module_name

这在 sub_module_*/ 中类似,其中不是 3 '..',而是只有两个(即 '..'、'..' 而不是 '..'、'..'、'..'对于上面的 sys.path.insert 行)。然后在 sub_module_a/useful_for_sub_module_a/useful_class_a.py 中,我必须像这样导入 module_name/constants.py(和其他):

import module_name.constants
from module_name.class_that_all_submodules_need_access_to import ImportantClass

虽然此解决方案有效,但我想知道是否有更好/更优雅的方式来设置导入和/或文件夹层次结构?我担心会为这个模块的用户弄乱 python 系统路径。这甚至是一个有效的担忧吗?

【问题讨论】:

    标签: python import python-import


    【解决方案1】:

    有两种 Python 导入:绝对和相对,请参阅Python import。但是导入的第一件事是你需要了解python是如何找到你的包的?如果你只是把你的包放在你的主文件夹下,那么 Python 对此一无所知。您可以查看此博客 [Python 搜索] (https://leemendelowitz.github.io/blog/how-does-python-find-packages.html)。

    因此要导入模块,首先要让 Python 知道你的包。在知道 Python 搜索包的位置后,通常有两种方法可以实现这一目标:

    (1) PYTHONPATH 环境变量。在您的环境配置文件中设置此变量,例如 .bash_profile。这也是最简单的方法。

    (2) 使用setuptools,它可以帮助您分发您的包裹。这是一个很长的故事。我不建议你选择它,除非你想在将来分发你的包。但是,值得了解。

    如果您正确设置路径,Python 导入就很简单了。如果您想使用绝对导入,请尝试

    from module_name import class_that_all_submodules_need_access_to
    

    如果你想使用相对导入,这取决于你现在是哪个模块。假设你正在写模块module_name.sub_module_a.sub_moduel_a_class_a,那么试试

    from .class_that_all_submodules_need_access_to import XX_you_want
    

    请注意,相对导入仅支持from .xx import xx 格式。

    谢谢。

    【讨论】:

    • 也只是复制到站点包文件夹是一个解决方案:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多