Python relative import with more than two dots

有些话、适合烂在心里 提交于 2019-12-07 01:10:12

问题


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.



来源:https://stackoverflow.com/questions/32395926/python-relative-import-with-more-than-two-dots

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