Python 中的 Pragmas

我正在读 bottle.py 的源代码。它是一个 web 框架,只有3000多行的 python 代码。太酷了。

我找到了这样的代码:

class ServerAdapter(object):
quiet = False
def __init__(self, host='127.0.0.1', port=8080, **config):
self.options = config
self.host = host
self.port = int(port)


def run(self, handler): # pragma: no cover
pass
...

# pragma: no cover是什么意思? 我在 Python 文档中找不到任何关于 pragma语法的介绍。

28641 次浏览

For Python, it's simply a comment. It might be an annotation targeted at some external tool, which reads and analyzes Python code, similar, for example, to doctest's #doctest: +ELLIPSIS annotations or PyLint's # pylint: disable=W0613 style annotations.

It is apparenly related to the coverage.py:

Coverage.py is a tool for measuring code coverage of Python programs. It monitors your program, noting which parts of the code have been executed, then analyzes the source to identify code that could have been executed but was not.

That exact # pragma: no cover is the hint that the part of code should be ignored by the tool -- see Excluding code from coverage .