gpt4 book ai didi

python - 添加相互依赖的 python 模块作为 git 子模块

转载 作者:行者123 更新时间:2023-11-30 22:59:11 24 4
gpt4 key购买 nike

我在 2 个独立的 git 存储库中有这 2 个小模块:

RepoA/A.py

def foo():
return "Hello World"

RepoB/B.py

import sys
try:
import A
except ImportError:
print("Dependency not available!")
sys.exit(1)

def bar():
return A.foo() + " EXTENDED!"

您会看到 B 当前假定 A 是全局可导入的(无论是已安装还是在脚本执行目录中)。

两者的根目录都有一个空的__init__py,使它们可以作为子模块导入。

现在我有另一个更大的存储库 C,它需要 B。它有 A 和 B 可用作 git 子模块,因此结构实际上如下所示:

RepoC
|---utils/
| |---__init__.py
| |---RepoA/
| | |---__init__.py
| | |---A.py
| |---RepoB/
| |---__init__.py
| |---B.py
|---C.py

RepoC/C.py

import utils.B

print(B.bar())

RepoC/utils/__init__.py

# remove the 1-layer indirection through the submodule
from .RepoB import B

现在,这将打印 Dependency not available!,正如预期的那样,因为 A 不是全局可用的,而是位于 B 永远无法使用的位置猜测(在这种情况下,需要执行 from ..RepoA import A)。如果我通过将 A 添加到 sys.path 使其再次全局可用,它将起作用:

RepoC/utils/__init__.py

import os, sys
import inspect

def fake_install(module_path):
# the submitted module path is relative to the caller's location
# therefore get that script's file location first
caller_module = inspect.getmodule(inspect.stack()[1][0])
caller_dir = caller_module.__file__.rsplit(os.path.sep, 1)[0]
# build an absolute file path and append it to the system paths
path = os.path.join(os.path.abspath(caller_dir), *module_path.split("."))
sys.path.append(path)

fake_install("RepoA")

# remove the 1-layer indirection through the submodule
from .RepoB import B

但这感觉像是一个可怕的解决方案。

另一个想法是根本不使用 git 子模块,而只是将依赖项作为 git-links 收集在requirements.txt中,编写一些setup.exe脚本并让pip实际安装它们。

如何优雅地解决这个问题?有什么导入技巧可以让我做到这一点吗?

最佳答案

正如您可能已经猜到的那样,我认为您有两个选择:要么让 A 和 B 成为 C 的一部分,要么使 B 和 C 独立包。

pip 的工作就是“将 A 放在 sys.path 中的某个位置”,所以你不妨让他来做这件事,而不是你自己做。您可以在需求中使用 git 链接,但不能在 setup.py 中使用,因此,如果您有更多的依赖项(D 需要 B,而 B 需要 C),并且您无法在 PyPI 上发布这些依赖项,您可能需要一个私有(private) PyPI 服务器(devpi对此效果很好)。

关于python - 添加相互依赖的 python 模块作为 git 子模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35858955/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com