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

编程入门 行业动态 更新时间:2024-10-27 17:09:58
本文介绍了何时或为何在 Python 中使用相对导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何关于何时在 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 中使用相对导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-03-31 17:20:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/808892.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:或为   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!