5. Python代碼和項目文檔
為什么需要記錄Python代碼?項目文檔應(yīng)該包括什么?如何編寫和生成文檔?
文檔是軟件開發(fā)的重要組成部分。如果沒有適當?shù)奈臋n,內(nèi)部和外部利益相關(guān)者可能很難或不可能使用或維護我們的代碼。這也使得新加入的開發(fā)人員變得更加困難。甚至自己也看不懂自己寫下的代碼。
1 注釋 vs 文檔
文檔是一個獨立的資源,可以幫助其他人使用我們的API、程序包、庫或框架等,而無需閱讀源代碼。而注釋是供閱讀源代碼的開發(fā)人員使用的。文檔應(yīng)該告訴其他人:
- 什么時候用
- 怎么用
而注釋應(yīng)該告訴其他人:
- 這是啥?
- 這個函數(shù)做了什么?
- 為什么這樣做?等。
2 Docstrings
Python的docstring是一種特殊的字符串,它作為模塊、函數(shù)、類或方法定義中的第一條語句出現(xiàn),形成給定對象的__doc__屬性。它使您可以將文檔直接嵌入到源代碼中:
"""
The?temperature?module:?Manipulate?your?temperature?easily
Easily?calculate?daily?average?temperature
"""
from?typing?import?List
class?HighTemperature:
????"""Class?representing?very?high?temperatures"""
????def?__init__(self,?value:?float):
????????"""
????????:param?value:?value?of?temperature
????????"""
????????self.value?=?value
def?daily_average(temperatures:?List[float])?->?float:
????"""
????Get?average?daily?temperature
????Calculate?average?temperature?from?multiple?measurements
????:param?temperatures:?list?of?temperatures
????:return:?average?temperature
????"""
????return?sum(temperatures)?/?len(temperatures)
我們可以看到daily_average的__doc__屬性:
>>>?from?temperature?import?daily_average
>>>
>>>?print(daily_average.__doc__)
????Get?average?daily?temperature
????:param?temperatures:?list?of?temperatures
????:return:?average?temperature
我們可以用內(nèi)置的help查看更詳細的信息:
>>>?import?temperature
>>>
>>>?help(temperature)
我們可以通過docstrings指定:
- 函數(shù)參數(shù)
- 函數(shù)返回
- 類屬性
- 異常
- 邊界或限制
- 示例代碼等
比較流行的文檔風(fēng)格:
- Google[1]
- reStructuredText[2]
- Numpy[3]
- Epytext[4]
選擇一種適合自己的文檔風(fēng)格,或者自定義一種屬于自己的風(fēng)格,使我們的項目更清晰。
3 Sphinx
將docstrings添加到代碼中是很棒的,但是仍然需要將它呈現(xiàn)給用戶。
這時就是Sphinx,Epydoc和MKDocs等工具發(fā)揮作用的時候了,這些工具會將項目的文檔字符串轉(zhuǎn)換為HTML和CSS。
Sphinx是迄今為止最受歡迎的。它被用于為許多開源項目生成文檔(例如Python和Flask)。它也是Read the Docs支持的文檔工具之一,僅舉幾例,它被數(shù)千個開源項目使用(如Requests,Flake8和pytest等)。
沒安裝的可以使用pip安裝,一起看看怎么用:
$?sphinx-quickstart?--version
sphinx-quickstart?3.5.4
在我們項目文件夾下新建一個temperature.py,添加上文提到的代碼,然后運行:
$?sphinx-quickstart?docs
>?Separate?source?and?build?directories?(y/n)?[n]:?n
>?Project?name:?Temperature
>?Author?name(s):?JKL
>?Project?release?[]:?1.0.0
>?Project?language?[en]:?en
這將會生成docs文件夾以及文件夾下面的一些文件。
更改docs/source/conf.py,將以下代碼:
#?import?os
#?import?sys
#?sys.path.insert(0,?os.path.abspath('.'))
改為:
import?os
import?sys
sys.path.insert(0,?os.path.abspath('../..'))
在extensions列表添加:
extensions?=?[
????'sphinx.ext.autodoc',
]
修改docs/source/index.rst:
..?Temperature?documentation?master?file,?created?by
???sphinx-quickstart?on?Sat?Apr?24?14:11:59?2021.
???You?can?adapt?this?file?completely?to?your?liking,?but?it?should?at?least
???contain?the?root?`toctree`?directive.
Welcome?to?Temperature's?documentation!
=======================================
..?toctree::
???:maxdepth:?2
???:caption:?Contents:
..?automodule::?temperature
??????:members:
Indices?and?tables
==================
*?:ref:`genindex`
*?:ref:`modindex`
*?:ref:`search`
進入docs文件夾下執(zhí)行:
$?make?html
html文檔就創(chuàng)建成功了。瀏覽器打開docs/build/html/index.html我們將會看到:

然后我們就可以更進一步,將我們的文檔上傳到類似Read the Docs[5]的網(wǎng)站了。
4 API文檔
API文檔有URL、URL參數(shù)、查詢參數(shù)、狀態(tài)碼、請求主體和響應(yīng)主體等。即使是簡單的API,也可能具有許多難以記住的參數(shù)。
OpenAPI給我們提供了一個好看而且使用的文檔。我們可以通過yaml或者json文件指定我們的api,OpenAPI會為我們自動生成好看的文檔。

FastAPI[6]就是一個很好的示例。
5 總結(jié)
本篇介紹了注釋與文檔的區(qū)別,使用sphinx生成文檔,簡單介紹了OpenAPI生成api文檔。為了使我們的項目讓別人(甚至自己)輕松理解和使用,開始動手寫文檔吧。
更多文檔請參考 www.testdriven.io[7]
參考資料
[1]Google: https://github.com/google/styleguide/blob/gh-pages/pyguide.md#38-comments-and-docstrings
[2]reStructuredText: https://docutils.sourceforge.io/rst.html
[3]Numpy: https://numpydoc.readthedocs.io/en/latest/format.html
[4]Epytext: http://epydoc.sourceforge.net/epytext.html
[5]Read the Docs: https://readthedocs.org/
[6]FastAPI: https://fastapi.tiangolo.com/
[7]更多文檔: https://testdriven.io/blog/documenting-python/
