[英]python - import namespace
If I have a library like: 如果我有一个像这样的图书馆:
MyPackage: MyPackage:
__init__.py
SubPackage1 子包装1
__init__.py
__init__.py
But I want that users can import moduleA like import MyPackage.moduleA
directly. 但是我希望用户可以像直接
import MyPackage.moduleA
一样import MyPackage.moduleA
moduleA。 Can I implement this by write some rules in MyPackage/__init__.py
? 我可以通过在
MyPackage/__init__.py
编写一些规则来实现这MyPackage/__init__.py
吗?
In MyPackage/__init__.py
, import the modules you want available from the subpackages: 在
MyPackage/__init__.py
,从子包中导入所需的模块:
from __future__ import absolute_import # Python 3 import behaviour
from .SubPackage1 import moduleA
from .SubPackage2 import moduleD
This makes both moduleA
and moduleD
globals in MyPackage
. 这使得
MyPackage
moduleA
和moduleD
都moduleA
全局变量。 You can then use: 然后,您可以使用:
from MyPackage import moduleA
and that'll bind to the same module, or do 然后将其绑定到相同的模块,或者
import MyPackage
myPackage.moduleA
to directly access that module. 直接访问该模块。
However, you can't use 但是,您不能使用
from MyPackage.moduleA import somename
as that requires moduleA
to live directly in MyPackage; 因为这要求
moduleA
直接存在于MyPackage中; a global in the __init__
won't cut it there. __init__
中的一个全局__init__
不会在那里切掉。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.