如何使用Python的文档字符串记录带有参数的方法?
编辑:
PEP 257给出了这样一个例子:
def complex(real=0.0, imag=0.0):
"""Form a complex number.
Keyword arguments:
real -- the real part (default 0.0)
imag -- the imaginary part (default 0.0)
"""
if imag == 0.0 and real == 0.0: return complex_zero
...
这是大多数Python开发人员使用的约定吗?
Keyword arguments:
<parameter name> -- Definition (default value if any)
我还以为你会更正式一点呢,比如
def complex(real=0.0, imag=0.0):
"""Form a complex number.
@param: real The real part (default 0.0)
@param: imag The imaginary part (default 0.0)
"""
if imag == 0.0 and real == 0.0: return complex_zero
...
环境:Python 2.7.1
在类型提示回答(https://stackoverflow.com/a/9195565/2418922)的基础上,它提供了一种更好的结构化方式来记录参数类型,还有一种结构化的方式来记录参数的类型和描述:
def copy_net(
infile: (str, 'The name of the file to send'),
host: (str, 'The host to send the file to'),
port: (int, 'The port to connect to')):
pass
示例:https://pypi.org/project/autocommand/
约定:
PEP 257文档字符串约定
PEP 287 reStructuredText文档字符串格式
工具:
Epydoc:为Python自动生成API文档
autodoc -包括文档字符串中的文档
PyCharm对文档字符串有一些很好的支持
更新:从Python 3.5开始,你可以使用类型提示,这是一种紧凑的、机器可读的语法:
from typing import Dict, Union
def foo(i: int, d: Dict[str, Union[str, int]]) -> int:
"""
Explanation: this function takes two arguments: `i` and `d`.
`i` is annotated simply as `int`. `d` is a dictionary with `str` keys
and values that can be either `str` or `int`.
The return type is `int`.
"""
这种语法的主要优点是它是由语言定义的,并且是明确的,因此像PyCharm这样的工具可以很容易地利用它。