Docstring约定是在
PEP-257比PEP-8更详细的细节。
然而,docstrings似乎比其他代码领域更加个人化。不同的项目将有自己的标准。
我倾向于总是包括docstrings,因为他们倾向于演示如何使用函数和它做得很快。
我喜欢保持一致,不管字符串的长度。我喜欢在缩进和间距一致时如何编写代码。这意味着,我使用:
def sq(n):
"""
Return the square of n.
"""
return n * n
过度:
def sq(n):
"""Returns the square of n."""
return n * n
并且倾向于在更长的文档字符串中排除对第一行的注释:
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
意思我发现docstrings,这样开始是凌乱。
def sq(n):
"""Return the squared result.
...