我有以下功能:
def my_func():
"""My docstring is both funny and informative"""
pass
如何访问文档字符串?
我有以下功能:
def my_func():
"""My docstring is both funny and informative"""
pass
如何访问文档字符串?
当前回答
import ast
import sys
f = open(sys.argv[1], "r") #filename input
module = ast.parse(f.read())
class_definitions = [node for node in module.body if isinstance(node, ast.ClassDef)]
method_definitions = []
for class_def in class_definitions:
print(class_def.name)
print(ast.get_docstring(class_def))
function_definitions = [node for node in class_def.body if isinstance(node, ast.FunctionDef)]
for f in function_definitions:
print('\t---')
print('\t'+f.name)
print('\t---')
print('\t'+'\t'.join(ast.get_docstring(f).splitlines(True)))
print('----')
其他回答
在ipython或jupyter笔记本上,你可以使用上面提到的所有方法,但我同意
my_func?
or
?my_func
方法签名和文档字符串的快速摘要。
我避免使用
my_func??
(正如@rohan所评论的那样)用于docstring,并且仅用于检查源代码
你也可以使用inspect.getdoc。它通过将制表符规范化为空格并左移文档主体以删除公共前导空格来清理__doc__。
交互地,您可以用
help(my_func)
或者从代码中检索它(用print(.)包围它以获得格式化输出):
my_func.__doc__
import ast
import sys
f = open(sys.argv[1], "r") #filename input
module = ast.parse(f.read())
class_definitions = [node for node in module.body if isinstance(node, ast.ClassDef)]
method_definitions = []
for class_def in class_definitions:
print(class_def.name)
print(ast.get_docstring(class_def))
function_definitions = [node for node in class_def.body if isinstance(node, ast.FunctionDef)]
for f in function_definitions:
print('\t---')
print('\t'+f.name)
print('\t---')
print('\t'+'\t'.join(ast.get_docstring(f).splitlines(True)))
print('----')