将包安装为子模块
我有一个第三方开源包“foo”;目前处于测试阶段,我想根据我的要求进行调整。因此,我不想将其安装在 /usr/local/lib/python 或当前 sys.path 中的任何位置,因为我无法在顶级包中进行频繁的更改。
foo/
__init__.py
fmod1.py
import foo.mod2
fmod2.py
pass
我想将包“foo”安装为命名空间“team.my_pkg”的子包。这样包的“全名”就变成了“team.my_pkg.foo”,而无需更改将“team.my_pkg.foo”引用为“foo”的内部模块中的代码。
team/
__init__.py
my_pkg/
__init__.py
foo/
fmod1.py
import foo.mod2
fmod2.py
pass
一种方法是在 team.my_pkg.init.py 中执行此操作:
import os.path
import sys
sys.path.append(os.path.dirname(__file__))
但我认为这是非常不安全的。我希望有某种方法,只有 fmod1.py 和 fmod2.py 可以通过其短名称调用“foo”,其他所有内容都应该使用其完整名称“team.my_pkg.foo”
我的意思是这应该在 team/my_pkg/foo 之外失败:
import team.my_pkg
import foo
但这应该在 team/my_pkg/foo 之外成功:
import team.my_pkg.foo
I have a package 3rd party open source package "foo"; that is in beta phase and I want to tweak it to my requirements. So I don't want to get it installed in /usr/local/lib/python or anywhere in current sys.path as I can't make frequent changes in top level packages.
foo/
__init__.py
fmod1.py
import foo.mod2
fmod2.py
pass
I want to install the the package "foo" as a sub package of my namespace say "team.my_pkg". So that the "fullname" of the package becomes "team.my_pkg.foo" without changing the code in inner modules that refer "team.my_pkg.foo" as "foo".
team/
__init__.py
my_pkg/
__init__.py
foo/
fmod1.py
import foo.mod2
fmod2.py
pass
One way to do this is to do this in team.my_pkg.init.py:
import os.path
import sys
sys.path.append(os.path.dirname(__file__))
But I think it is very unsafe. I hope there is some way that only fmod1.py and fmod2.py can call "foo" by its short name everything else should use its complete name "team.my_pkg.foo"
I mean this should fail outside team/my_pkg/foo:
import team.my_pkg
import foo
But this should succeed outside team/my_pkg/foo:
import team.my_pkg.foo
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有什么问题:
What is wrong with:
使用显式相对导入允许可重定位子包引用自身。例如在 fmod1.py 中:
Use explicit relative imports to allow relocatable subpackages to refer to themselves. eg in fmod1.py: