Python 模块的绝对与显式相对导入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4209641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Absolute vs. explicit relative import of Python module
提问by Daniel Hepper
I'm wondering about the preferred way to import packages in a Python application. I have a package structure like this:
我想知道在 Python 应用程序中导入包的首选方法。我有一个这样的包结构:
project.app1.models
project.app1.views
project.app2.models
project.app1.viewsimports project.app1.modelsand project.app2.models. There are two ways to do this that come to mind.
project.app1.views进口project.app1.models和project.app2.models。有两种方法可以做到这一点。
With absolute imports:
使用绝对进口:
import A.A
import A.B.B
or with explicit relative imports, as introduced in Python 2.5 with PEP 328:
或使用显式相对导入,如Python 2.5 中引入的PEP 328:
# explicit relative
from .. import A
from . import B
What is the most pythonic way to do this?
什么是最pythonic的方式来做到这一点?
采纳答案by Rafe Kettler
Absolute imports. From PEP 8:
绝对进口。来自 PEP 8:
Relative imports for intra-package imports are highly discouraged. Always use the absolute package path for all imports. Even now that PEP 328 [7] is fully implemented in Python 2.5, its style of explicit relative imports is actively discouraged; absolute imports are more portable and usually more readable.
非常不鼓励包内导入的相对导入。始终对所有导入使用绝对包路径。即使现在 PEP 328 [7] 在 Python 2.5 中完全实现,其显式相对导入的风格也被积极劝阻;绝对导入更便携,通常更易读。
Explicit relative imports are a nice language feature (I guess), but they're not nearly as explicit as absolute imports. The more readable form is:
显式相对导入是一个很好的语言特性(我猜),但它们不像绝对导入那样明确。更易读的形式是:
import A.A
import A.B.B
especially if you import several different namespaces. If you look at some well written projects/tutorials that include imports from within packages, they usually follow this style.
特别是如果您导入多个不同的命名空间。如果您查看一些包含从包内导入的编写良好的项目/教程,它们通常遵循这种风格。
The few extra keystrokes you take to be more explicit will save others (and perhaps you) plenty of time in the future when they're trying to figure out your namespace (especially if you migrate to 3.x, in which some of the package names have changed).
当其他人(也许还有你)试图找出你的命名空间时(特别是如果你迁移到 3.x,其中一些包名字变了)。
回答by Brandon Rhodes
Relative imports not only leave you free to rename your package later without changing dozens of internal imports, but I have also had success with them in solving certain problems involving things like circular imports or namespace packages, because they do not send Python "back to the top" to start the search for the next module all over again from the top-level namespace.
相对导入不仅让您以后可以自由地重命名您的包,而无需更改数十个内部导入,而且我还成功地解决了涉及循环导入或命名空间包之类的某些问题,因为它们不会将 Python“送回” top”从顶级命名空间重新开始搜索下一个模块。
回答by Stefano
Python relative imports are no longer strongly discouraged, but using absolute_import is strongly suggested in that case.
不再强烈反对 Python 相对导入,但强烈建议在这种情况下使用 absolute_import。
Please see this discussionciting Guido himself:
请参阅引用 Guido 本人的讨论:
"Isn't this mostly historical? Until the new relative-import syntax was implemented there were various problems with relative imports. The short-term solution was to recommend not using them. The long-term solution was to implement an unambiguous syntax. Now it is time to withdraw the anti-recommendation. Of course, without going overboard -- I still find them an acquired taste; but they have their place."
“这不是大部分历史吗?在实现新的相对导入语法之前,相对导入存在各种问题。短期解决方案是建议不要使用它们。长期解决方案是实现明确的语法。现在是时候撤回反建议了。当然,不要过分——我仍然觉得它们是后天习得的;但它们有自己的位置。”
The OP correctly links the PEP 328that says:
OP 正确链接了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.
介绍了几个用例,其中最重要的是能够重新排列大包的结构而无需编辑子包。此外,如果没有相对导入,包内的模块无法轻松导入自身。
Also see almost duplicate question When or why to use relative imports in Python
另请参阅几乎重复的问题何时或为什么在 Python 中使用相对导入
Of course it still stands as a matter of taste. While it's easier to move code around with relative imports, that might also unexpectedly break things; and renaming the imports is not that difficult.
当然,它仍然是一个品味问题。虽然使用相对导入来移动代码更容易,但这也可能出乎意料地破坏事情;重命名导入并不困难。
To force the new behaviour from PEP 328 use:
要强制 PEP 328 中的新行为,请使用:
from __future__ import absolute_import
In this case, implicit relative import will no longer be possible (eg. import localfilewill not work anymore, only from . import localfile). For clean and future proof behaviour, using absolute_import is advisable.
在这种情况下,隐式相对导入将不再可能(例如,import localfile将不再起作用,只有from . import localfile)。对于干净且面向未来的行为,建议使用 absolute_import。
An important caveat is that because of PEP 338and PEP 366, relative imports require the python file to be imported as a module - you cannot execute a file.py that has a relative import or you'll get a ValueError: Attempted relative import in non-package.
一个重要的警告是,由于 PEP 338和PEP 366,相对导入需要将 python 文件作为模块导入 - 您不能执行具有相对导入的 file.py 或者您将获得ValueError: Attempted relative import in non-package.
This limitation should be taken into account when evaluating the best approach. Guido is against running scripts from a module in any case:
在评估最佳方法时应考虑到这一限制。Guido 在任何情况下都反对从模块运行脚本:
I'm -1 on this and on any other proposed twiddlings of the __main__ machinery. The only use case seems to be running scripts that happen to be living inside a module's directory, which I've always seen as an antipattern. To make me change my mind you'd have to convince me that it isn't.
我对这个和 __main__ 机器的任何其他提议的摆弄都是 -1。唯一的用例似乎是运行恰好位于模块目录中的脚本,我一直将其视为反模式。为了让我改变主意,你必须让我相信事实并非如此。
Exhaustive discussions on the matter can be found on SO; re. Python 3 this is quite comprehensive:
关于这个问题的详尽讨论可以在 SO 上找到;关于。Python 3 这是相当全面的:

