Python 模块的绝对与显式相对导入

时间:2023-04-17
本文介绍了Python 模块的绝对与显式相对导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想知道在 Python 应用程序中导入包的首选方式.我有一个这样的包结构:

I'm wondering about the preferred way to import packages in a Python application. I have a package structure like this:

project.app1.models
project.app1.views
project.app2.models

project.app1.views 导入 project.app1.modelsproject.app2.models.我想到了两种方法.

project.app1.views imports project.app1.models and project.app2.models. There are two ways to do this that come to mind.

使用绝对导入:

import A.A
import A.B.B

或使用显式相对导入,如 带有 PEP 328 的 Python 2.5:

or with explicit relative imports, as introduced in Python 2.5 with PEP 328:

# explicit relative
from .. import A
from . import B

最pythonic的方法是什么?

What is the most pythonic way to do this?

推荐答案

绝对导入.从 PEP 8:

Absolute imports. From PEP 8:

包内导入的相对导入高度灰心.始终对所有导入使用绝对包路径.即使现在 PEP 328 [7] 已在 Python 2.5 中完全实现,积极劝阻其明确的相对进口风格;绝对导入更便携,通常更易读.

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.

显式相对导入是一个不错的语言功能(我猜),但它们不像绝对导入那样显式.更易读的形式是:

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.

您为了更明确而采取的一些额外击键将为其他人(也许还有您)在将来尝试找出您的命名空间时节省大量时间(特别是如果您迁移到 3.x,其中一些包名称已更改).

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).

这篇关于Python 模块的绝对与显式相对导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:如何删除使用 Python 的 easy_install 安装的软件包? 下一篇:列出作为 python 包一部分的所有模块?

相关文章