简体   繁体   English

Python / Git /模块结构最佳实践

[英]Python / Git / Module structure best practice

We have a lot small projects that share common utility "projects" 我们有许多共享公用程序“项目”的小项目

Example : 范例
utility project math contains function add 实用项目数学包含功能添加
project A and project B both need math.add 项目A和项目B都需要math.add
project A has nothing to do with project B 项目A与项目B无关

so is it a good idea to have 3 git repositories (project_A,project_B and math) and clone them locally as 所以拥有3个git存储库(project_A,project_B和math)并在本地将其克隆为一个好主意是

/SOMWHERE/workspace/project_A
/SOMWHERE/workspace/math

and have in /SOMWHERE/workspace/project_A/__init__.py something like 并在/SOMWHERE/workspace/project_A/__init__.py中有类似

import sys
sys.path.append('../math')
import math

math.add()

I have read Structuring Your Project but that doesn't handle SCM and sharing modules. 我已经阅读了“ 构建项目”,但是无法处理SCM和共享模块。

So to sum up my question: is 所以总结一下我的问题:是

sys.path.append('../math')    
import math

good practice or is there a more "pythonic" way of doing that? 好的做法还是有一种更“ pythonic”的方式来做到这一点?

Submodules are a suboptimal way of sharing modules like you said in your comments. 子模块是共享模块的次佳方式,就像您在评论中所说的那样。 A better way would be to use the tools offered by your language of choice, ie Python. 更好的方法是使用您选择的语言(即Python)提供的工具。

First, create virtualenvs to isolate every project python environment. 首先, 创建virtualenvs来隔离每个项目python环境。 Use pip to install packages and store dependencies in a requirements.txt file. 使用pip安装软件包并将依赖项存储在requirements.txt文件中。

Then, you can create a specific package for each of your utils library using distutils and share it on Pypi . 然后,您可以使用distutils为每个utils库创建一个特定的程序包,在Pypi上共享它

If you don't want to release your packages into the wild, you can also host your own Pypi server . 如果您不希望将软件包发布到野外,也可以托管自己的Pypi服务器

Using this setup, you will be able to use different versions of your libraries and work on them without breaking compatibility with older code bases. 使用此设置,您将能够使用不同版本的库并对其进行处理,而不会破坏与旧代码库的兼容性。 You will also avoid using submodules, that are difficult to use with git. 您还将避免使用难以与git一起使用的子模块。

all of what you describe (3 projects) sounds fine except that you shouldn't mess around with sys.path . 您所描述的所有内容(3个项目)听起来都不错, 只是您不应该乱用sys.path instead, set the PYTHONPATH environment variable. 而是设置PYTHONPATH环境变量。

also, if you were not aware of distutils i am guessing you may be new to python development, and may not know about virtualenv. 另外,如果您不了解distutils,我想您可能是python开发的新手,并且可能不了解virtualenv。 you should use that too (it allows you to develope against a "clean" python version that has no packages, or only the packages you install for that env). 您也应该使用它(它允许您针对不包含任何软件包或仅针对该env安装的软件包的“干净” python版本进行开发)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM