3C科技 娛樂遊戲 美食旅遊 時尚美妝 親子育兒 生活休閒 金融理財 健康運動 寰宇綜合

Zi 字媒體

2017-07-25T20:27:27+00:00
加入好友
在軟體工程中,其實編碼所佔的部分是非常小的,大多是其它的事情,比如寫文檔。文檔是溝通的工具。在 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 paramReturns: This is a description of what is returnedRaises: KeyError - raises an exception"""Numpydoc (Numpy 風格)"""My numpydoc description of a kindof very exhautive numpydoc format docstring.Parametersfirst : array_like the 1st param name `first`second : the 2nd paramthird : {'value', 'other'}, optional the 3rd param, by default 'value'Returns-------string a value in a stringRaises------KeyError when a key errorOtherError 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.看效果: 題圖:pexels,CC0 授權。

本文由yidianzixun提供 原文連結

寫了 5860316篇文章,獲得 23313次喜歡
精彩推薦