[英]Getting the docstring from a function
I have the following function:我有以下 function:
def my_func():
"""My docstring is both funny and informative"""
pass
How do I get access to the docstring?如何访问文档字符串?
Interactively, you can display it with交互式地,您可以使用
help(my_func)
Or from code you can retrieve it with或者您可以从代码中检索它
my_func.__doc__
You can also use inspect.getdoc
.您也可以使用inspect.getdoc
。 It cleans up the __doc__
by normalizing tabs to spaces and left shifting the doc body to remove common leading spaces.它通过将制表符规范化为空格并左移文档正文以删除常见的前导空格来清理__doc__
。
On ipython or jupyter notebook, you can use all the above mentioned ways, but i go with在 ipython 或 jupyter notebook 上,您可以使用上述所有方法,但我使用
my_func?
or或者
?my_func
for quick summary of both method signature and docstring.快速总结方法签名和文档字符串。
I avoid using我避免使用
my_func??
(as commented by @rohan) for docstring and use it only to check the source code (如@rohan 所评论)用于 docstring 并仅将其用于检查源代码
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('----')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.