2017年8月25日 / 15,834次阅读
Python
程序员一直以来都有一个烦恼,他们只想写代码,不想写文档。他们说:代码就表达了我的思想和灵魂。
小公司相对随意一些,可以先写代码调试,但是最后老板害怕程序员离职造成“青黄不接”,还是会要求补上文档。大公司要求更高,要先写文档,评审通过,然后再开始编码。有的程序员整天都在写文档,苦不堪言。
Python提出了一个方案,叫docstring,来试图解决这个问题。即编写代码,同时也能写出文档,保持代码和文档的一致。
Python提出的这个方案其实并不新鲜,docstring说白了就是一堆代码中的注释。任何编程语言都有注释的好不好!!不过,Python的docstring可以通过help函数直接输出一份有格式的文档,这个就厉害了。代码写完,注释写完,一个help调用,就有文档看了。
docstring可以写在三个地方:模块或包,对象,函数。
(以下示例使用著名的requests包)
对于模块,docstring就是在模块文件的最前面,如下示例:
# -*- coding: utf-8 -*-
"""
requests.api
~~~~~~~~~~~~
This module implements the Requests API.
:copyright: (c) 2012 by Kenneth Reitz.
:license: Apache2, see LICENSE for more details.
"""
from . import sessions
docstring使用三个双引号(”),triple double quote for docstring,这是PEP0257里的约定。
对于包,docstring就是在package的__init__.py这个文件的任何语句的前面(docstring的前面还可以有#注释),如下示例:
# -*- coding: utf-8 -*-
# __
# /__) _ _ _ _ _/ _
# / ( (- (/ (/ (- _) / _)
# /
"""
Requests HTTP Library
~~~~~~~~~~~~~~~~~~~~~
Requests is an HTTP library, written in Python, for human beings. Basic GET
usage:
>>> import requests
>>> r = requests.get('https://www.python.org')
>>> r.status_code
200
>>> 'Python is a programming language' in r.content
True
... or POST:
>>> payload = dict(key1='value1', key2='value2')
>>> r = requests.post('http://httpbin.org/post', data=payload)
>>> print(r.text)
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}
The other HTTP methods are supported - see `requests.api`. Full documentation
is at <http://python-requests.org>.
:copyright: (c) 2017 by Kenneth Reitz.
:license: Apache 2.0, see LICENSE for more details.
"""
import urllib3
对于函数,docstring就是在函数定义的最前面,如下示例:
def get(url, params=None, **kwargs):
r"""Sends a GET request.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', True)
return request('get', url, params=params, **kwargs)
注意上例的三个双引号前有个r,r是raw的意思,表示这个字符串里面的\就是它自己,不是用来转意的。
对于对象定义,docstring就是在class定义的最前面,如下示例:
class Timeout(RequestException):
"""The request timed out.
Catching this error will catch both
:exc:`~requests.exceptions.ConnectTimeout` and
:exc:`~requests.exceptions.ReadTimeout` errors.
"""
class ConnectTimeout(ConnectionError, Timeout):
"""The request timed out while trying to connect to the remote server.
Requests that produced this error are safe to retry.
"""
还有一种单行docstring的写法,如下:
def getStartLink():
"""get start link"""
startLink = str()
# get start link value
if __name__ == "__main__":
Python builtin的help函数主要是在交互模式下使用,在交互模式下,使用help,就能够看到文档中的这些被称为docstring的注释,被一种良好的格式显示出来。
在调整代码的时候,维护注释,维护docstring,进而保持代码和文档(help函数的输出)一致,麦新杰认为是一种简化的思想。docstring不是强制的,如果不写,help函数的输出就是空空的。
下面是help(requests)的输出:
>>>
>>> import requests
>>> help(requests)
Help on package requests:
NAME
requests
DESCRIPTION
Requests HTTP Library
~~~~~~~~~~~~~~~~~~~~~
Requests is an HTTP library, written in Python, for human beings. Basic GET
usage:
>>> import requests
>>> r = requests.get('https://www.python.org')
>>> r.status_code
200
>>> 'Python is a programming language' in r.content
True
... or POST:
>>> payload = dict(key1='value1', key2='value2')
>>> r = requests.post('http://httpbin.org/post', data=payload)
>>> print(r.text)
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}
The other HTTP methods are supported - see `requests.api`. Full documentatio
n
is at <http://python-requests.org>.
:copyright: (c) 2017 by Kenneth Reitz.
:license: Apache 2.0, see LICENSE for more details.
PACKAGE CONTENTS
__version__
_internal_utils
adapters
api
auth
看description部分,这就是写requests包的__init__.py文档中的docstring。
而且还可以看出,help函数不仅输出docstring,还有一些其它的格式化的输出信息,非常handy呀。
专业的Python docstring文档,请参考PEP257
您可能要先看一下:什么是PEP文档?
Python这种语言简单易学,有个原因就是它将一些复杂的事情简化了,比如非强制的docstring,比如强制缩进。
本文链接:https://www.maixj.net/ict/python-docstring-16247
《使用Python的docstring》有2条留言
©Copyright 麦新杰 Since 2014 云上小悟独立博客版权所有 备案号:苏ICP备14045477号-1。云上小悟网站部分内容来源于网络,转载目的是为了整合信息,收藏学习,服务大家,有些转载内容也难以判断是否有侵权问题,如果侵犯了您的权益,请及时联系站长,我会立即删除。
Always use """triple double quote""" for docstring. [ ]
docstring同时也是python的多行注释。 [ ]