![](/img/trans.png)
[英]How would I improve this simple python class and its docstring ?
[英]How would I pretty print a python docstring?
我有一个python文件,其原始字符串作为docstrings。
def a():
'\n\tthis\n\tis\n\tthe docstring.\n\t'
print 'hello world'
我如何重写docstring看起来像
def a():
"""
this
is
the docstring.
"""
print 'hello world'
这是使用inspect.getsoucelines
和一些正则表达式的示例:
import inspect
import re
def update_doc(func, indent=' '):
sourcelines = inspect.getsourcelines(func)[0]
doc = func.__doc__
if doc is not None:
ind = [line.decode('string_escape').strip()[1:-1]
for line in sourcelines].index(doc)
sourcelines[ind] = '{}"""{}"""\n'.format(indent,
re.sub(r'\n([ \t]+)', r'\n'+indent, doc))
return ''.join(sourcelines)
演示:
def a():
'\n\tthis\n\tis\n\tthe docstring.\n\t'
print 'hello world'
print update_doc(a)
def b():
'\n This is\n not so lengthy\n docstring\n '
print 'hmm...'
print update_doc(b)
输出:
def a():
"""
this
is
the docstring.
"""
print 'hello world'
def b():
"""
This is
not so lengthy
docstring
"""
print 'hmm...'
PS:我还没有彻底测试过,但这应该让你开始。
Pyment允许创建,协调和转换文档字符串。
它目前无法将原始描述扩展为\\n
,但可以轻松添加此功能。 您可以打开一个问题来申请。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.