Ecco un esempio utilizzando il inspect.getsoucelines
e alcuni regex:
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)
uscita:
def a():
"""
this
is
the docstring.
"""
print 'hello world'
def b():
"""
This is
not so lengthy
docstring
"""
print 'hmm...'
P.S: Non ho ancora testato a fondo, ma questo dovrebbe iniziare.
fonte
2014-07-15 21:34:55
Questo mi fa chiedere come sia stata scritta la docstring in quel modo. Sembra che sarebbe meglio aggiustarlo alla fonte (dato che non conosco nessun essere umano che scrive docstring in quel modo ;-) – mgilson
dopo un 'ast.NodeTransform' e non riesco a ottenere il generatore di codice per scriverlo nel bel formato senza riscrivere tutte le stringhe. – baallezx
Cosa intendi esattamente per bella stampa? Ovviamente interpretare sequenze di escape, ma anche indentazione, word wrapping, conformità a [PEP 257] (http://legacy.python.org/dev/peps/pep-0257/), ...? In tal caso, * elenca * i tuoi requisiti per tale trasformazione in modo esplicito. –