問題描述
是否有任何關于何時在 Python 中使用相對導入的規則或指南?我一直在使用它們,就像在 Flask Web 框架中一樣.在搜索這個主題時,我只看到有關如何使用相對導入的文章,而沒有看到為什么.
Is there any rules or guidelines concerning when to use relative imports in Python? I see them in use all the time like in the Flask web framework. 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
而不是:
from package import x
此外,我注意到相關的 SO 帖子 提到不鼓勵相對導入.然而人們仍在繼續使用它們.
Moreover, I noticed that a related SO post mentions that relative imports are discouraged. Yet people still continue to use them.
推薦答案
查看 PEP 328 關于相對進口的部分
理由似乎是這樣寫的:
展示了幾個用例,其中最重要的是能夠重新排列大型包的結構,而無需編輯子包.此外,包內的模塊在沒有相對導入的情況下無法輕松導入自身.
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.
這篇關于何時或為什么在 Python 中使用相對導入的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!