問題描述
是否有任何關(guān)于何時(shí)在 Python 中使用相對(duì)導(dǎo)入的規(guī)則或指南?我一直在使用它們,就像在 Flask Web 框架中一樣.在搜索這個(gè)主題時(shí),我只看到有關(guān)如何使用相對(duì)導(dǎo)入的文章,而沒有看到為什么.
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
此外,我注意到相關(guān)的 SO 帖子 提到不鼓勵(lì)相對(duì)導(dǎo)入.然而人們?nèi)栽诶^續(xù)使用它們.
Moreover, I noticed that a related SO post mentions that relative imports are discouraged. Yet people still continue to use them.
推薦答案
查看 PEP 328 關(guān)于相對(duì)進(jìn)口的部分
理由似乎是這樣寫的:
展示了幾個(gè)用例,其中最重要的是能夠重新排列大型包的結(jié)構(gòu),而無需編輯子包.此外,包內(nèi)的模塊在沒有相對(duì)導(dǎo)入的情況下無法輕松導(dǎo)入自身.
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.
這篇關(guān)于何時(shí)或?yàn)槭裁丛?Python 中使用相對(duì)導(dǎo)入的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!