重用python代码的最佳实践 [英] Best practice for reusing python code

查看:106
本文介绍了重用python代码的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个python库应用程序(其中包含多个* .py文件)。我的一些python项目需要重用库应用中的代码。建议重用python代码的最佳做法是什么?目前,我已经考虑了三个选项:

I have write a python library app(which contains several *.py files). And several of my python projects need to reuse the code in the library app. What's the recommended best practice for reusing python code? Currently I have thought out three options:


  1. 复制并粘贴。这与最佳实践相去甚远。它违反了
    DRY原则。(请勿重复。)

  2. 将库应用的文件夹添加到环境变量PYTHONPATH中: export PYTHONPATH = / path / to / library / app 。然后,同一台计算机上的每个项目都可以引用库应用程序中的代码。

  3. 以及库应用程序文件夹的python代码为sys.path: sys。 path.append('/ path / to / library / app')

  1. Copy and paste. This is far away from best practice. It violates the DRY principle.(Don't repeat yourself.)
  2. Add the folder of the library app to the environment variable PYTHONPATH: export PYTHONPATH=/path/to/library/app. Then every projects on the same computer can reference the code in the library app.
  3. And the folder of the library app to sys.path in python code: sys.path.append('/path/to/library/app')

以上三个选项中的你更倾向哪个?与其他两个选项相比,它有什么优势?您还有其他更好的选择吗?非常感谢,如果有人具有多年的python开发经验,可以回答这个问题。

Among the three options above which one do you prefer? What advantage does it have compared to the other two options? Do you have any other better options? It is much appreciated that if some one with years of python development experiences could answer this question.

推荐答案

让我提出第四个选择:花时间学习如何打包您的库并将其安装在您的站点中,包装;它比人们想像的要容易,而且我坚信它已经花了很多时间。这是一个很好的起点: https://packaging.python.org/en/latest/

Allow me to propose a fourth alternative: take the time to learn how to package your library and install it in your site-packages; it's easier than one may think and I'm convinced it's time well spent. This is a very good starting point: https://packaging.python.org/en/latest/

这篇关于重用python代码的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆