Alexander Engelhardt
Alexander Engelhardt

Reputation: 1712

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, 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?

Upvotes: 6

Views: 4652

Answers (1)

Dorian Turba
Dorian Turba

Reputation: 3735

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

Upvotes: 3

Related Questions