Python relative import with more than two dots

2020-08-24 07:26发布

问题:

Is it ok to use a module referencing with more than two dots in a path? Like in this example:

# Project structure:
# sound
#     __init__.py
#     codecs
#         __init__.py
#     echo
#         __init__.py
#         nix
#             __init__.py
#             way1.py
#             way2.py

# way2.py source code
from .way1 import echo_way1
from ...codecs import cool_codec

# Do something with echo_way1 and cool_codec.

UPD: Changed the example. And I know, this will work in a practice. But is it a common method of importing or not?

回答1:

From PEP8:

Absolute imports are recommended, as they are usually more readable and tend to be better behaved (or at least give better error messages) if the import system is incorrectly configured (such as when a directory inside a package ends up on sys.path ):

import mypkg.sibling
from mypkg import sibling
from mypkg.sibling import example

However, 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:

from . import sibling
from .sibling import example

Standard library code should avoid complex package layouts and always use absolute imports.