我不确定我是否看到了这个问题的具体答案,但我有一个关于python文档字符串返回值的样式约定的问题。
考虑如下函数:
def foo(ex):
output = 2*ex
return output
在PyCharm中,如果我为这个函数制作了一个docstring,它看起来像:
def foo(ex):
"""
Sample text....
:param ex: description...
:return: description of return value
"""
output = 2*ex
return output
我的问题是我是否应该name我在docstring中的返回值?即
:return:返回值的描述
:return:输出:返回值的描述
这方面有编码标准吗?还是主要由个人偏好决定?
正如randomizer已经提到的,Python PEP没有指定文档字符串的内容应该如何结构化。然而,大型编码项目通常有自己的文档字符串内容指南,您可以调整其中一个。
就我个人而言,我喜欢Numpy文档字符串格式(请参阅此处和此处)。返回值的本地名称不包括在Numpy样式的文档字符串中。函数的文档字符串如下所示:
def foo(ex):
"""One-line function description.
Parameters
----------
ex : float
Description of parameter.
Returns
-------
float
Description of return value.
"""
output = 2*ex
return output
Sphinx文档生成器也支持Numpy风格的文档字符串。
实际上在PEP-257中定义了Docstring约定(PEP-8仅引用了它),但只涵盖了一般格式,没有涵盖内容。
文档字符串的内容通常由名为Sphinx的Python文档生成器进行解释,在Sphinx中,存在以下信息字段:
param
、parameter
、arg
、argument
、key
、keyword
:参数的描述type
:参数的类型。如果可能,创建一个链接raises
、raise
、except
、exception
:引发特定异常的时间var
、ivar
、cvar
:变量的描述vartype
:变量的类型。如果可能,创建一个链接returns
、return
:返回值的描述rtype
:返回类型。如果可能,创建一个链接
请注意返回类型的rtype
。
因此,您可以使用rtype
指定返回类型,但对象返回的实际(本地)名称无关紧要。
def foo(x):
"""Sample text.
:param x: parameter description
:type x: int
:return: description of return value
:rtype: int
"""
output = 2*ex
return output