2014-07-15 8 views
5

Ho un file python con stringhe non elaborate come docstring.Come potrei stampare una docstring python?

def a(): 
    '\n\tthis\n\tis\n\tthe docstring.\n\t' 
    print 'hello world' 

come faccio a riscrivere la docstring per assomigliare

def a(): 
    """ 
    this 
    is 
    the docstring. 
    """ 
    print 'hello world' 
+10

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

+2

dopo un 'ast.NodeTransform' e non riesco a ottenere il generatore di codice per scriverlo nel bel formato senza riscrivere tutte le stringhe. – baallezx

+1

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. –

risposta

2

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.

+0

Ma come potrei usarlo per riscrivere un file? Aggiungi questa funzione a ogni file e chiama questo metodo dopo ogni funzione, quindi usa qualcosa come sed per acquisire l'output e salvarlo in un nuovo file. – baallezx

1

Pyment consente di creare, armonizzare e convertire docstring.

Attualmente non è possibile proporre l'espansione della descrizione come \n, ma potrebbe essere facile aggiungere questa funzionalità. È possibile aprire un problema per richiederlo.