python - 需要帮助理解有关 Python 中相对导入和绝对导入的问题

标签 python import python-import

当我想在特定文件夹中安装某个 Python 包(使用 pip install -t),然后从该包导入模块时,出现错误。

我在包的 Github 上发布了这个问题,结果发现我无法在某个文件夹中安装包;不支持以这种方式安装软件包。

Even without google collab, I can reproduce the import error when trying to install sklearn in some specific folder with pip install -t sklearnFolder then importing it as sklearnFolder.sklearn.manifold.

That is not a supported way of installing / using scikit-lean. One reason why it wouldn't work is that a few modules in scikit-learn use absolute imports (e.g. from sklearn import something) which will fail with such setup.

You should either install it with pip install or if you want to have it in some specific folder, clone the repo to that folder, then run pip install -e , in both cases it will be imported as sklearn.

来自https://github.com/scikit-learn/scikit-learn/issues/11656

我不太明白这个解释。

我想的是这样的

from folderName.package import module

相同
from package import module

因为它们都是绝对进口的。如图所示,它们都完全指定了导入模块的路径。所以我的理解有一些问题,但我不知道它是什么。

最佳答案

在导入中,您不指定文件夹名称作为包的前缀。如果包已安装或位于 python 路径中,则只需使用包名称即可导入。

    # Assume the below structure is under a directory (folder) called /app/home/packages.

    reservation/                  This is your top-level pacakge 
        __init__.py               Initialize the package
        hotels/                   Subpackage for hotel reservations
            __init__.py
            slots.py
            bid.py
            demand.py
            ...
            restaurents/                  Another Subpackage under hotels 
                __init__.py
                cuisine.py
                hours.py
                tableslots.py
                ...
        rewards/                      Subpackage for rewards
            __init__.py
            points.py
            discounts.py
            membersonly.py
            ...

由于该包位于/app/home/packages 下,因此当您为文件夹名称添加前缀时,以下导入无效。

    from packages.reservation import hotels 

正确的导入方法是从具有包初始化 __init__.py 的实际包中导入。如果您在示例中看到,预订文件夹有 __init__.py。

    from reservation import hotels 

如果要导入hotels下的子模块,则需要加上package前缀:

   from reservation.hotels import restaurents

或者,您可以直接导入子模块,但在使用时必须添加包前缀:

   import reservation.hotels.restaurents

关于python - 需要帮助理解有关 Python 中相对导入和绝对导入的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51510407/

相关文章:

python - 如何使 wx 工具栏按钮变大?

objective-c - 进行循环引用导入时出错

python - 如何用matplotlib绘制条形图时间轴?

python - 为什么 python 允许为同一个类创建不同的属性集?

r - 导入不带行分隔符的固定宽度数据文件

sqlite - 将 .CSV 文件导入 SQLite

python - Python 中 "import as"的用例

python - CS50 Web 编程 - 导入 books.csv 文件时出现 Postgres SQL 错误

Python 项目结构和相关导入

python - 使用参数启动 gnome 终端