Python中的多行註解文檔編寫風格

高洛峰
發布: 2017-03-02 11:20:09
原創
1579 人瀏覽過

什麼是docstring

在軟體工程中,其實編碼所佔的部分是非常小的,大多是其它的事情,例如寫文件。文檔是溝通的工具。
在Python中,比較推崇在程式碼中寫文檔,程式碼即文檔,比較方便,容易維護,直觀,一致。
程式碼寫完,文檔也出來了。其實Markdown也差不多這種思想,文字寫完,排版也完成了。
看看PEP 0257中對docstring的定義:

A docstring is a string literal that occurs as the first statement in
a module, function, class, or method definition. Such a docstring
becomes the __doc__ special attribute of that object.
簡單來說,就是出現在模組、函數、類別、方法裡第一個語句的,就是docstring。會自動變成屬性__doc__。

def foo(): """ This is function foo"""
登入後複製

可透過foo.__doc__存取得到' This is function foo'.

各類docstring風格:

Epytext

這是曾經比較流行的一直類似javadoc的風格。

""" This is a javadoc style. @param param1: this is a first param @param param2: this is a second param @return: this is a description of what is returned @raise keyError: raises an exception """
登入後複製

reST

這是現在流行的一種風格,reST風格,Sphinx的御用格式。我個人也是喜歡用這種風格,比較緊湊。

""" This is a reST style. :param param1: this is a first param :param param2: this is a second param :returns: this is a description of what is returned :raises keyError: raises an exception """
登入後複製

Google風格

#
""" This is a groups style docs. Parameters: param1 - this is the first param param2 - this is a second param Returns: This is a description of what is returned Raises: KeyError - raises an exception """
登入後複製

Numpydoc (Numpy風格)

""" My numpydoc description of a kind of very exhautive numpydoc format docstring. Parameters ---------- first : array_like the 1st param name `first` second : the 2nd param third : {'value', 'other'}, optional the 3rd param, by default 'value' Returns ------- string a value in a string Raises ------ KeyError when a key error OtherError when an other error """
登入後複製

#docstring工具之第三方函式庫pyment

用來建立和轉換docstring.
使用方法就是用pyment產生一個patch,然後打patch。

$ pyment test.py #生成patch $ patch -p1 < test.py.patch #打patch
登入後複製

詳情:https://github.com/dadadel/pyment

使用sphinx的autodoc自動從docstring生產api文檔,不用再手寫一次

我在程式碼中已經寫過docstring了,寫api文檔的內容跟這個差不多,難道要一個一個拷貝過去rst嗎?當然不用。 sphinx有autodoc功能。
首先編輯conf.py文件,
1. 要有'sphinx.ext.autodoc'這個extensions
2. 確保需要自動生成文檔的模組可被import,即在路徑中。例如可能需要sys.path.insert(0, os.path.abspath('../..'))

然後,寫rst文件,

xxx_api module --------------------- .. automodule:: xxx_api :members: :undoc-members: :show-inheritance:
登入後複製

敲make html指令,就可以從docstring中產生相關的文件了,不用多手寫一遍rst.
看效果:

Python中的多行註解文檔編寫風格


更多Python中的多行註解文件編寫風格相關文章請關注PHP中文網!


相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!