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

坚强是说给别人听的谎言 提交于 2021-02-10 15:40:48

问题


I've recently created a Python package, and within it, used only relative imports to access functions stored in other methods.

Now, in Numpy, I see a lot of files that make heavy use of absolute imports, e.g. this file. It has a lot of statements like 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? Doesn't the absolute import require numpy to be already installed?


回答1:


Absolute vs Relative Imports in 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. In fact, PEP 8 explicitly recommends absolute imports.

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



来源:https://stackoverflow.com/questions/54218726/why-use-absolute-instead-of-relative-imports-in-a-python-package

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!