python是谁维护的_Python 库从开发到维护
每個法師都有一顆近戰的心,每個 CS 學生都有開發一個算法庫的小目標~
前言
在學習和開發過程中,筆者發現項目開發和庫開發有很大不同的,下面從 __init__.py 、單元測試、README、測試、文檔和 Pypi/Conda 幾方面分別介紹一個 Python 庫應當具備的內容。最開始項目目錄是這樣的:
|- .
|- torchcluster 庫名稱
|- __init__.py
|- dataset 用來放數據集
|- __init__.py
|- zoo 用來放算法
|- __init__.py
|- helper 用來放輔助函數
|- __init__.py
這套代碼是在做實驗的過程編寫的,傳統算法在 GPU 上的庫比較少,因此自己用 PyTorch 寫了譜聚類和 K-Means,正好可以拿來做成 Python 庫共享給要用的童鞋們~
__init__.py
大家都知道 __init__.py 會將文件夾轉化為 package 從而使文件夾下的所有 py 文件都可以被外界 import?,F在我們要寫一個庫啦,要更嚴謹一點,所以這里要注意對用戶可以 import 的內容進行限制:
# ./torchcluster/zoo/__init__.py
from .k_means import KMeans
from .spectrum import SpectrumClustering
?
__all__ = ('KMeans', 'SpectrumClustering')
此外,我們在使用庫的時候常常會用 .__version__ 查看版本,也要記得填上~
# ./torchcluster/__init__.py
?
from torchcluster import dataset
from torchcluster import zoo
?
__version__ = '0.1.3'
?
__all__ = ('dataset', 'zoo')
單元測試
單元測試是用來對模塊、函數或者類來進行檢查的測試。一個沒有單元測試的庫是沒人敢用的~ 自動化的單元測試可以幫助我們在修改部分代碼之后,高效的檢測整個庫是否有出錯的地方。這里我們選擇 pytest 完成單元測試~
第一步是建立一個 tests 文件夾:
|- .
|- tests 單元測試
|- test_method_name.py 這里要以 test_ 開頭~
|- torchcluster 庫名稱
|- ...
這里要注意 pytest 的三個要求:測試文件名必須以 test_ 開頭
測試類以 Test 開頭,并且不能帶有 init 方法
測試方法必須以 test_ 開頭
pytest 會自動運行負荷要求的模塊、函數或者類,捕捉到拋出的異常:
# ./tests/test_k_means.py 文件名稱
def test_k_means(): # 測試方法名稱
...
assert(True) # 正常的使用異常檢測
在寫單元測試的時候,我們會引用到 ../torchcluster 內的模塊,而 pytest 的運行目錄是 tests,直接運行 pytest 會造成向上級文件夾引用的錯誤,因此我們需要將庫中的 python 模塊用作腳本運行:
# 添加了 -m
python -m pytest tests/test_k_means.py
README
在寫 README 之前先說一下 LICENSE,自己寫的庫要聲明自己的版權,不然別人拿走改個名字說是他寫的怎么辦~ 我一般都是選用比較寬松的 MIT 許可證的,畢竟有人抄算是看得起我~ 在根目錄下建立一個名為 LICENSE 的文件就好了:
# ./LICENSE
The MIT License (MIT)
?
Copyright (c) 2019-present, Zhang Zhi
?
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
?
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
?
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
README.md 文件主要是在 github 首頁上顯示的,所以盡可能簡潔一點突出自己的庫的特點咯,我一般是分為四個部分:System requirement
Installaction
How torchcluster looks like / How to use
License
# torchcluster
[Documentation](...) |
...
## System requirements
torchcluster should work on
- all Linux distributions no earlier than Ubuntu 16.04
- macOS X
- Windows 10
torchcluster also requires Python 3.5 or later. Python 2 support is coming.
Right now, torchcluster works on [PyTorch](https://pytorch.org/) 0.4.1.
## Installation
...
## How torchcluster looks like
...
## License
[MIT](http://opensource.org/licenses/MIT)
Copyright (c) 2019-present, Zhang Zhi
因為 pypi 對 md 文件的支持比較差,所以我們需要手動將 md 文檔轉換成 rst 文檔,弄一個 README.rst 留給 pypi 首頁展示~ 推薦使用 convert?,F在項目文件夾就會變成這個樣子啦:
|- tests
|- ...
|- torchcluster
|- ...
|- .gitignore
|- LICENSE
|- README.md
|- README.rst
文檔
手寫文檔比較麻煩,所以很少有手寫文檔的大佬,像 PyTorch 這種熱門庫也都是根據注釋自動生成,然后再手動添加和修改的。這里我們選擇 docstring + sphinx。docstring 用來生成標準的注釋格式,sphinx 用來根據注釋提取模塊、方法和類的信息,生成文檔 html。
我是用 vscode 里面的 docstring 生成注釋格式的,其實復制粘貼再改一改也不麻煩:
# ./torchcluster/zoo/k_means.py
class KMeans(Cluster):
"""K-Means algorithm"""
# 上面是對類的注釋,包含簡介
def __init__(self, n_clusters, tol=1e-4):
"""Spectrum clustering factory's config.?Args:n_clusters (int) - How many clusters in result.?Kwargs:tol (float) - stop to update when shift is smaller than tol?"""
# 上面是對方法的注釋,包含簡介、帶關鍵字的參數和不帶關鍵字的參數
super(KMeans, self).__init__()
self.n_clusters = n_clusters
self.tol = tol
?
def __call__(self, x):
"""Clustering.?Args:x (Tensor) - Data points of number n by feature dim m."""
然后再項目目錄下運行:
pip install sphinx
sphinx-quickstart docs
# 執行期間 sphinx 會詢問你各項設置,如果不懂默認也可以
# 記得下面的這一條一定要 yes,不然沒法自動生成文檔
# autodoc: automatically insert docstrings from modules (y/n) [n] y
sphinx 會在根目錄下創建 docs 目錄,用于存放構建文件、配置文件、模板和內容等等:
|- docs
|- _build
|- static
|- _templates
conf.py
make.bat
makefile
這里需要對 conf 添加一些附加配置:
# ./docs/conf.py
html_theme = 'sphinx_rtd_theme'
# -- Extension configuration -------------------------------------------------
autoclass_content = 'both'
?
import sys
from unittest.mock import MagicMock
?
class Mock(MagicMock):
@classmethod
def __getattr__(cls, name):
return MagicMock()
?
# 如果還有其他庫也要加在下面
MOCK_MODULES = [
'numpy',
'scipy',
'sklearn',
'matplotlib',
'matplotlib.pyplot',
'scipy.interpolate',
'scipy.special',
'math'
]
sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES)
其中 html_theme 是用來修改頁面樣式的,這個樣式算是文檔比較通用的了。
autoclass_content 是為了在自動生成文檔之后顯示 __init__.py 的內容的(默認省略)。
Mock 可以幫助我們在構建文檔時不引入代碼內的依賴庫,而是模擬一個依賴庫。你在本地或許有安裝依賴,但是使用遠程自動構建的時候就不一定有了,會造成各種 timeout~
現在可以運行:
make html
然后打開 ./docs/_build/index.html 頁面查看效果啦~文檔頁面
每次 build 完手動把 html 文件傳到自己服務器或者 github page 太麻煩了,因此我選擇使用 readthedoc。將項目傳到 github 上,然后再 readthedoc 點擊 import a Project 就可以了:導入項目
盡管我們已經 mock 了代碼中引用的庫,為了保險起見建議在管理-高級設置中進行如下配置:管理-高級設置
然后點擊構建版本進行構建,復制閱讀文檔的鏈接到 README.md 和 README.rst 就好了:構建
Pypi 和 Conda
接下來我們要把庫上傳到 pypi 和 conda 上,這樣別人就能像使用 PyTorch 一樣安裝我們的庫啦~
pip install torchcluster
conda install -c tczhangzhi torchcluster
針對 conda 我們需要定義 meta.yaml:
{% set version = "0.1.3" %}
?
package:
name: torchcluster
version: {{ version }}
?
build:
noarch: generic
?
requirements:
run:
- python
- pytorch
- numpy
?
about:
home: https://github.com/tczhangzhi/cluster
license: MIT
summary: 'Torchcluster is a python package for cluster analysis.'
description: |
Torchcluster is a python package for cluster analysis. The speed of the clustering algorithm has been effectively improved with the Pytorch backend. We are also working on test datasets and visualization tools. Related work is coming in the next release.
這里需要注意的是,由于我們的項目依賴支持所有平臺,而沒有引入其他基于系統的代碼,所以我們可以直接使用 noarch: generic 讓 mac、win 和 linux 都可以下載使用。之后運行:
conda build .
就可以自動構建啦,構建完成后 conda 會提示你上傳的命令,復制下來跑一下就行了。
針對 Pypi 我們需要定義 setup.py 和 http://MANIFEST.in,其中 http://MANIFEST.in 是定義保留文件的:
# MANIFEST.in
include LICENSE
include README.md
setup.py 是定義各種構建配置的,這里 packages 一定要記得 find_packages 哦:
from setuptools import setup, find_packages
?
requirements = [
'numpy',
'torch',
]
?
readme = open('README.rst').read()
?
setup(
name='torchcluster',
version='0.1.3',
description='Torchcluster is a python package for cluster analysis.',
license='MIT',
author='Zhi Zhang',
author_email='850734033@qq.com',
keywords=['pytorch', 'cluster'],
url='https://github.com/tczhangzhi/cluster',
packages=find_packages(exclude=['tests']),
long_description=readme,
setup_requires=requirements
)
都定義好之后運行下面的命令就可以自動打包上傳了:
python setup.py register sdist upload
維護
Github 上的各路大佬可能會給你提 Issues,要及時回復和修復~ 修復完之后記得修改 __init__.py、setup.py 和 meta.yaml 中的版本號,重新打包上傳。回復 issues
結尾
如果有什么不懂的可以直接翻看項目中的相關源代碼,項目地址是:tczhangzhi/cluster。
作為研究人員,開發出像 DGL 一樣優秀的算法庫應該也算是一種科研成就叭。革命尚未成功,同志仍需努力,高效、功能強大的算法庫少不了 C++ 和 CUDA 的支持,后面會補上相關內容。
總結
以上是生活随笔為你收集整理的python是谁维护的_Python 库从开发到维护的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 装饰器分类_Python
- 下一篇: python函数递归年龄_Python学