简体   繁体   English

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

[英]Why use absolute instead of relative imports in a Python package?

I've recently created a Python package, and within it, used only relative imports to access functions stored in other methods. 我最近创建了一个Python包,并且在其中仅使用相对导入来访问存储在其他方法中的函数。

Now, in Numpy, I see a lot of files that make heavy use of absolute imports, eg this file . 现在,在Numpy中,我看到很多大量使用绝对导入的文件 ,例如this file It has a lot of statements like from numpy.core import overrides . 它有很多语句,例如from numpy.core import overrides

I don't see a disadvantage in using relative imports. 我看不到使用相对导入的缺点。 Why are they doing it like that, instead of from ..core import overrides ? 他们为什么这样做,而不是from ..core import overrides Doesn't the absolute import require numpy to be already installed? 绝对导入是否需要已安装numpy?

Absolute vs Relative Imports in Python Python中的绝对导入和相对导入

Absolute Import 绝对进口

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. 此外,即使import语句的当前位置更改,绝对导入仍然有效。 In fact, PEP 8 explicitly recommends absolute imports. 实际上,PEP 8明确建议绝对导入。

Sometimes, however, absolute imports can get quite verbose, depending on the complexity of the directory structure. 但是,有时绝对导入可能会变得非常冗长,具体取决于目录结构的复杂性。

Relative Import 相对进口

One clear advantage of relative imports is that they are quite succinct. 相对进口的一个明显优势是它们非常简洁。

Unfortunately, relative imports can be messy, particularly for shared projects where directory structure is likely to change. 不幸的是,相对导入可能比较混乱,尤其是对于目录结构可能会更改的共享项目。 Relative imports are also not as readable as absolute ones, and it's not easy to tell the location of the imported resources. 相对导入也没有绝对导入更易读,而且很难说出导入资源的位置。

PEP8 : about Imports PEP8关于进口

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM