Pythonでdocstringを書くいくつかの異なるスタイルを見てきましたが、最も人気のあるスタイルは何ですか?
6 に答える
フォーマット
Python docstringは、他の投稿が示しているように、いくつかの形式に従って記述できます。ただし、デフォルトのSphinx docstring形式は言及されておらず、 reStructuredText(reST)に基づいています。このブログ投稿で主な形式に関する情報を入手できます。
reSTはPEP287によって推奨されていることに注意してください
docstringの主な使用形式は次のとおりです。
-Epytext
歴史的には、javadocのようなスタイルが普及していたため、ドキュメントを生成するためのEpydoc(呼び出されたEpytext形式)のベースとして使用されていました。
例:
"""
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
"""
- 残り
現在、おそらくより一般的な形式は、Sphinxがドキュメントを生成するために使用するreStructuredText(reST)形式です。注:これは、JetBrains PyCharmでデフォルトで使用されます(メソッドを定義してEnterキーを押した後、三重引用符を入力します)。これは、デフォルトでPymentの出力形式としても使用されます。
例:
"""
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には、よく使用される独自の形式があります。また、Sphinxで解釈することもできます(つまり、Napoleonプラグインを使用します)。
例:
"""
This is an example of Google style.
Args:
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は、Google形式に基づいており、Sphinxで使用できる独自のnumpydocに従うことをお勧めします。
"""
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
"""
変換/生成
Pymentなどのツールを使用して、まだ文書化されていないPythonプロジェクトへのdocstringを自動的に生成したり、既存のdocstring(複数の形式を混在させることができる)を形式から別の形式に変換したりすることができます。
Googleスタイルガイドには、優れたPythonスタイルガイドが含まれています。これには、PEP-257よりも優れたガイダンスを提供する読み取り可能なdocstring構文の規則が含まれています。例えば:
def square_root(n):
"""Calculate the square root of a number.
Args:
n: the number to get the square root of.
Returns:
the square root of n.
Raises:
TypeError: if n is not a number.
ValueError: if n is negative.
"""
pass
このSphinxドキュメントチュートリアルで説明されているように、これを拡張して引数に型情報も含めるようにします。例えば:
def add_value(self, value):
"""Add a new value.
Args:
value (str): the value to add.
"""
pass
Docstringの規則は、 PEP -8よりもはるかに詳細なPEP-257にあります。
ただし、docstringは、他のコード領域よりもはるかに個人的なもののようです。プロジェクトごとに独自の基準があります。
関数の使用方法と関数の動作を非常にすばやく示す傾向があるため、私は常にdocstringを含める傾向があります。
文字列の長さに関係なく、一貫性を保つことを好みます。インデントと間隔が一貫している場合の外観のコーディング方法が好きです。つまり、私は以下を使用します。
def sq(n):
"""
Return the square of n.
"""
return n * n
以上:
def sq(n):
"""Returns the square of n."""
return n * n
そして、長いdocstringの最初の行へのコメントを省く傾向があります。
def sq(n):
"""
Return the square of n, accepting all numeric types:
>>> sq(10)
100
>>> sq(10.434)
108.86835599999999
Raises a TypeError when input is invalid:
>>> sq(4*'435')
Traceback (most recent call last):
...
TypeError: can't multiply sequence by non-int of type 'str'
"""
return n*n
つまり、このように始まるdocstringは乱雑だと思います。
def sq(n):
"""Return the squared result.
...
明らかに誰もそれについて言及していません:NumpyDocstringStandardを使用することもできます。科学界で広く使用されています。
- numpyからのフォーマットの仕様と例
- あなたはそれをレンダリングするためのスフィンクス拡張を持っています:numpydoc
- そして、レンダリングされたdocstringがどれほど美しく見えるかの例:http://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html
Googleスタイルのdocstringを解析するためのNapoleansphinx拡張機能(@Nathanの回答で推奨)もNumpyスタイルのdocstringをサポートし、両方を簡単に比較します。
そして最後に、それがどのように見えるかを理解するための基本的な例を示します。
def func(arg1, arg2):
"""Summary line.
Extended description of function.
Parameters
----------
arg1 : int
Description of arg1
arg2 : str
Description of arg2
Returns
-------
bool
Description of return value
See Also
--------
otherfunc : some related other function
Examples
--------
These are written in doctest format, and should illustrate how to
use the function.
>>> a=[1,2,3]
>>> print [x + 3 for x in a]
[4, 5, 6]
"""
return True
Pythonです。何でも行きます。ドキュメントを公開する方法を検討してください。Docstringは、ソースコードの読者以外には表示されません。
人々は本当にウェブ上のドキュメントを閲覧して検索するのが好きです。これを実現するには、ドキュメントツールSphinxを使用します。これは、Pythonプロジェクトを文書化するためのデファクトスタンダードです。製品は美しいです-https://python-guide.readthedocs.org/en/latest/を見てください。ウェブサイトReadtheDocsは、ドキュメントを無料でホストします。
VladimirKeleshevのpep257Pythonプログラムを使用して、DocstringをPEP-257およびNumpy Docstring Standardと照合し、パラメーターやリターンなどを記述することをお勧めします。
pep257は、標準からの逸脱を報告し、pylintやpep8のように呼ばれます。