2020年8月30日 / 782次阅读 / Last Modified 2020年9月1日
代码就是最好的文档,python的docstring,应该是要好好编写和维护的。本文内容是对PEP257的理解和总结。PEP257只是说明了docstring的convention,要不要按照这个convention来写docstring,程序员有自由。但是如果按照这个convention来写docstring,能够得到一些好处,比如pydoc。
import之后,docstring的内容,存放在对象的__doc__属性中。
docstring习惯上用 triple double quote (""") 括起来!
对 package,module,function,class,method(class中的),都要写docstring。package的docstring写在__init__.py这个文件中,写法跟在module中写一样。
PEP257中提到的 attribute docstring 和 additional docstring,我暂时选择了忽略。保持简单很重要!
对应package的__init__.py文件和module(就是.py文件),docstring写在文件的最开始。如果有#!,写在#!后面。
其它对象的docstring,都写在对象定义位置的下一行。下面有例子。
对于class的docstring,PEP257中有说到一个细节,即写完docstring后,空一行,再写def __init__(self)。这里的空一行,应该是PEP8的内容,属于code layout。
很简单,就一行。这样:""" 内容 """,所有符号都在一行内。
def kos_root():
"""Return the pathname of the KOS root directory."""
global _kos_root
if _kos_root: return _kos_root
...
一般 package和module的docstring,不应该会写成oneline的。
多行docstring有一些说道:
Multi-line docstrings consist of a summary line just like a one-line docstring, followed by a blank line, followed by a more elaborate description. The summary line may be used by automatic indexing tools; it is important that it fits on one line and is separated from the rest of the docstring by a blank line. The summary line may be on the same line as the opening quotes or on the next line. The entire docstring is indented the same as the quotes at its first line (see example below).
elaborate description部分,我看网上贴出来不同公司的风格,这些都是细节了。python自带的pydoc,貌似对中间的空行不做特别处理,但是有些更高级的工具会处理中间这个空行。所以,还是请保持这个空行吧,看着看着就习惯了。
如下这三种情况,都属于多行docstring:
def foo():
"""A multi-line
docstring.
"""
def bar():
"""
A multi-line
docstring.
"""
def zxy():
"""
A multi-line docstring, no more description.
"""
写docstring,是为了用pydoc直接导出文档,代码就是你的文档。不过,也有情况可以不用写。
下划线开头的function, class和method,我觉得是可以不用写docstring的。因为在用pydoc导出的时候,下划线开头的这些对象,不会输出。习惯上这些都是内部使用的对象,根据情况,我觉得是可以不写docstring的。
-- EOF --
本文链接:https://www.pynote.net/archives/2427
前一篇:Email批量发送工资条的方案
后一篇:用pydoc查看导出docstring
©Copyright 麦新杰 Since 2019 Python笔记