Python Import – How to Use Relative Imports in Modules

importpythonrelative-path

I'm taking my first stab at a library, and I've noticed the easiest way to solve the issue of intra-library imports is by using constructions like the following:

from . import x
from ..some_module import y

Something about this strikes me as 'bad.' Maybe it's just the fact that I can't remember seeing it very often, although in fairness I haven't poked around the guts of a ton of libraries.

Just wanted to see if this is considered good practice and, if not, what's the better way to do this?

Best Answer

There is a PEP for everything.

Quote from PEP8: Imports

Explicit relative imports are an acceptable alternative to absolute imports, especially when dealing with complex package layouts where using absolute imports would be unnecessarily verbose:

Guido's decision in PEP328 Imports: Multi-Line and Absolute/Relative

Copy Pasta from PEP328

Here's a sample package layout:

package/
    __init__.py
    subpackage1/
        __init__.py
        moduleX.py
        moduleY.py
    subpackage2/
        __init__.py
        moduleZ.py
    moduleA.py

Assuming that the current file is either moduleX.py or subpackage1/__init__.py , the following are all correct usages of the new syntax:

from .moduleY import spam
from .moduleY import spam as ham
from . import moduleY
from ..subpackage1 import moduleY
from ..subpackage2.moduleZ import eggs
from ..moduleA import foo
from ...package import bar
from ...sys import path