我见过Python中编写文档字符串的几种不同风格,最流行的风格是什么?
当前回答
我建议使用Vladimir Keleshev的pep257 Python程序根据PEP-257和Numpy Docstring标准检查文档字符串,以描述参数,返回值等。
Pep257将报告您与标准的差异,并被称为pylint和pep8。
其他回答
文档字符串约定在PEP-257中比PEP-8详细得多。
然而,文档字符串似乎比其他代码区域更加个性化。不同的项目会有自己的标准。
我总是倾向于包含文档字符串,因为它们倾向于快速演示如何使用函数以及它的功能。
我更喜欢保持一致,不管字符串的长度。我喜欢如何编码时,缩进和间距是一致的。这意味着,我使用:
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
这意味着我发现像这样开始的文档字符串是混乱的。
def sq(n):
"""Return the squared result.
...
我建议使用Vladimir Keleshev的pep257 Python程序根据PEP-257和Numpy Docstring标准检查文档字符串,以描述参数,返回值等。
Pep257将报告您与标准的差异,并被称为pylint和pep8。
这是Python;任何事情都可能发生。考虑如何发布您的文档。除了源代码的读者,文档字符串是不可见的。
人们真的很喜欢在网上浏览和搜索文档。要实现这一点,请使用文档工具Sphinx。它是记录Python项目的事实上的标准。产品很漂亮-看看https://python-guide.readthedocs.org/en/latest/。“阅读文档”网站将免费保存你的文档。
显然没有人提到它:你也可以使用Numpy文档字符串标准。它被广泛应用于科学界。
numpy格式的规范以及一个示例 您有一个sphinx扩展来渲染它:numpydoc 一个漂亮的文档字符串的示例:http://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html
用于解析google风格文档字符串的Napolean sphinx扩展(在@Nathan的回答中推荐)也支持numpy风格的文档字符串,并对两者进行了简短的比较。
最后是一个基本的例子来说明它是怎样的:
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风格指南。它包含了可读文档字符串语法的约定,提供了比PEP-257更好的指导。例如:
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
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象