Python模块的绝对和显式相对导入 [英] Absolute vs. explicit relative import of Python module

查看:79
本文介绍了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

最Python化的方法是什么?

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模块的绝对和显式相对导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆