将包安装为子模块

发布于 2024-10-09 11:32:40 字数 958 浏览 0 评论 0原文

我有一个第三方开源包“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

著墨染雨君画夕 2024-10-16 11:32:40
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.

有什么问题:

python setup.py develop
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.

What is wrong with:

python setup.py develop
谁人与我共长歌 2024-10-16 11:32:40

使用显式相对导入允许可重定位子包引用自身。例如在 fmod1.py 中:

from . import mod2

Use explicit relative imports to allow relocatable subpackages to refer to themselves. eg in fmod1.py:

from . import mod2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文