![](/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.