search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

如何寫出優雅的 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.

看效果:

題圖:pexels,CC0 授權。



熱門推薦

本文由 yidianzixun 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦