問題描述
我想知道在 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.models
和 project.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 模塊的絕對與顯式相對導入的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!