[英]How would I pretty print a python docstring?
I have a python file that has raw strings as the docstrings. 我有一个python文件,其原始字符串作为docstrings。
def a():
'\n\tthis\n\tis\n\tthe docstring.\n\t'
print 'hello world'
how would I rewrite the docstring to look like 我如何重写docstring看起来像
def a():
"""
this
is
the docstring.
"""
print 'hello world'
Here's an example using the inspect.getsoucelines
and some regex: 这是使用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)
Demo: 演示:
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)
Output: 输出:
def a():
"""
this
is
the docstring.
"""
print 'hello world'
def b():
"""
This is
not so lengthy
docstring
"""
print 'hmm...'
PS: I have not tested it thoroughly yet, but this should get you started. PS:我还没有彻底测试过,但这应该让你开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.