gpt4 book ai didi

python - 为什么在 Python 包中使用绝对导入而不是相对导入?

转载 作者:行者123 更新时间:2023-12-05 05:12:48 24 4
gpt4 key购买 nike

我最近创建了一个 Python 包,并在其中仅使用相对导入来访问存储在其他方法中的函数。

现在,在 Numpy 中,我看到很多文件大量使用绝对导入,例如this file .它有很多语句,例如 from numpy.core import overrides

我不认为使用相对导入有什么缺点。他们为什么这样做,而不是 from ..core import overrides?绝对导入不要求已经安装了 numpy 吗?

最佳答案

Absolute vs Relative Imports in Python

绝对导入

Absolute imports are preferred because they are quite clear and straightforward. It is easy to tell exactly where the imported resource is, just by looking at the statement. Additionally, absolute imports remain valid even if the current location of the import statement changes. In fact, PEP 8 explicitly recommends absolute imports.

Sometimes, however, absolute imports can get quite verbose, depending on the complexity of the directory structure.

相对导入

One clear advantage of relative imports is that they are quite succinct.

Unfortunately, relative imports can be messy, particularly for sharedprojects where directory structure is likely to change. Relativeimports are also not as readable as absolute ones, and it’s not easyto tell the location of the imported resources.

PEP8 : about Imports

关于python - 为什么在 Python 包中使用绝对导入而不是相对导入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54218726/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com