带有两个以上点的Python相对导入 [英] Python relative import with more than two dots
问题描述
可以使用在路径中引用两个以上点的模块吗?像这个例子一样:
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::更改了示例。我知道,这将在实践中起作用。但这是一种常见的导入方法吗?
UPD: Changed the example. And I know, this will work in a practice. But is it a common method of importing or not?
推荐答案
从 PEP8 :
绝对导入是建议,因为如果导入系统配置不正确(例如,程序包中的目录最终位于sys.path时),则它们通常更具可读性,并且往往表现更好(或至少会提供更好的错误消息):
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.
这篇关于带有两个以上点的Python相对导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!