我不知道有任何用于 python 文档字符串的静态分析工具。事实上,我在开始使用 PyLint 后不久就开始构建一个,但很快就放弃了。
PyLint 有一个插件系统,如果您想投入工作以使 PEP 可执行,则可以使用文档字符串插件。
PyLint“插件”称为检查器,有两种形式:将源文件作为原始文本文档使用的插件和将源文件作为 AST 使用的插件。我从 AST 开始尝试。回想起来,这可能是一个错误。
这是我所拥有的:
class DocStringChecker(BaseChecker):
"""
PyLint AST based checker to eval compliance with PEP 257-ish conventions.
"""
__implements__ = IASTNGChecker
name = 'doc_string_checker'
priority = -1
msgs = {'W9001': ('One line doc string on >1 lines',
('Used when a short doc string is on multiple lines')),
'W9002': ('Doc string does not end with "." period',
('Used when a doc string does not end with a period')),
'W9003': ('Not all args mentioned in doc string',
('Used when not all arguments are in the doc string ')),
'W9004': ('triple quotes',
('Used when doc string does not use """')),
}
options = ()
def visit_function(self, node):
if node.doc: self._check_doc_string(node)
def visit_module(self, node):
if node.doc: self._check_doc_string(node)
def visit_class(self, node):
if node.doc: self._check_doc_string(node)
def _check_doc_string(self, node):
self.one_line_one_one_line(node)
self.has_period(node)
self.all_args_in_doc(node)
def one_line_one_one_line(self,node):
"""One line docs (len < 80) are on one line"""
doc = node.doc
if len(doc) > 80: return True
elif sum(doc.find(nl) for nl in ('\n', '\r', '\n\r')) == -3: return True
else:
self.add_message('W9001', node=node, line=node.tolineno)
def has_period(self,node):
"""Doc ends in a period"""
if not node.doc.strip().endswith('.'):
self.add_message('W9002', node=node, line=node.tolineno)
def all_args_in_doc(self,node):
"""All function arguments are mentioned in doc"""
if not hasattr(node, 'argnames'): return True
for arg in node.argnames:
if arg != 'self' and arg in node.doc: continue
else: break
else: return True
self.add_message('W9003', node=node, line=node.tolineno)
def triple_quotes(self,node): #This would need a raw checker to work b/c the AST doesn't use """
"""Doc string uses tripple quotes"""
doc = node.doc.strip()
if doc.endswith('"""') and doc.startswith('"""'): return True
else: self.add_message('W9004', node=node, line=node.tolineno)
def register(linter):
"""required method to auto register this checker"""
linter.register_checker(DocStringChecker(linter))
我记得这个系统没有很好的文档(可能在过去的一年里发生了变化)。这至少为您提供了一些东西来开始破解/非常简单的代码来代替文档。