简体   繁体   English

何时或为何在 Python 中使用相对导入

[英]When or why to use relative imports in Python

Is there any rules or guidelines concerning when to use relative imports in Python?是否有任何关于何时在 Python 中使用相对导入的规则或指南? I see them in use all the time like in the Flask web framework.我看到它们一直在使用,就像在 Flask Web 框架中一样。 When searching for this topic, I only see articles on how to use relative imports, but not why .在搜索这个主题时,我只看到关于如何使用相对导入的文章,但没有看到为什么

So is there some special benefit to using:那么使用是否有一些特殊的好处:

from . import x

rather than:而不是:

from package import x

Moreover, I noticed that on this SO question, the answer mentions that relative imports are discouraged.此外,我注意到在这个SO 问题上,答案提到不鼓励相对进口。 Yet people still continue to use them.然而人们仍然继续使用它们。

Check out PEP 328's section on relative imports查看PEP 328 关于相对导入的部分

The rationale seems to be as written:理由似乎是这样写的:

Several use cases were presented, the most important of which is being able to rearrange the structure of large packages without having to edit sub-packages.介绍了几个用例,其中最重要的是能够重新排列大包的结构而无需编辑子包。 In addition, a module inside a package can't easily import itself without relative imports.此外,如果没有相对导入,包内的模块无法轻松导入自身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM