简体   繁体   中英

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.

Now, in Numpy, I see a lot of files that make heavy use of absolute imports, eg 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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