解析Python模块Docstrings

2024-10-04 05:28:12 发布

您现在位置:Python中文网/ 问答频道 /正文

可以用AST解析模块级docstring吗?在

我正在研究一个python文档管理器here,访问模块令牌并获取文档不会生成模块级docstring。到目前为止,我不得不求助于导入模块并获取它的__doc__,或者使用inspect来获取文档。在

我在pydoc module源代码中寻找其他文档编制者如何解析docstring的线索,发现pydoc最终不得不做与我的文档编制者基本相同的事情,才能获取模块级字符串。在

我错过什么了吗?是通过实际导入模块来解析模块级docstring的唯一方法,还是可以直接从AST解析docstring?在


Tags: 模块文档管理器dochere源代码ast事情
1条回答
网友
1楼 · 发布于 2024-10-04 05:28:12

也许我没能理解这个问题,但你就不能这么做(Python2.7.1)?在

测试文件:

"""
DOC STRING!!
"""

def hello():
    'doc string'
    print 'hello'

hello()

互动环节:

^{pr2}$

您还可以遍历ast,寻找doc字符串所在的插槽。在

>>> M._fields
('body',)
>>> M.body
[<_ast.Expr object at 0x10e5ac710>, <_ast.FunctionDef object at 0x10e5ac790>, <_ast.Expr object at 0x10e5ac910>]
>>> # doc would be in the first slot
>>> M.body[0]._fields
('value',)
>>> M.body[0].value
<_ast.Str object at 0x10e5ac750>
>>> # it contains a string object, so maybe it's the doc string
>>> M.body[0].value._fields
('s',)
>>> M.body[0].value.s
'\nDOC STRING!!\n'

相关问题 更多 >