Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I pretty print a python docstring?

I have a python file that has raw strings as the docstrings.

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

how would I rewrite the docstring to look like

def a():
    """
    this
    is
    the docstring.
    """
    print 'hello world'
like image 424
baallezx Avatar asked Jul 15 '14 20:07

baallezx


People also ask

How do I show a docstring in Python?

Docstrings are accessible from the doc attribute (__doc__) for any of the Python objects and also with the built-in help() function. An object's docstring is defined by including a string constant as the first statement in the object's definition.

Can you format a docstring Python?

Python docstrings can be written following several formats as the other posts showed. However the default Sphinx docstring format was not mentioned and is based on reStructuredText (reST). You can get some information about the main formats in that tuto. There follows the main used formats for docstrings.

How do you make a good Python docstring?

Class method docstrings should contain the following: A brief description of what the method is and what it's used for. Any arguments (both required and optional) that are passed including keyword arguments. Label any arguments that are considered optional or have a default value.

How do you print a docstring of a inbuilt function in Python?

just use print(input. doc)


2 Answers

Here's an example using the inspect.getsoucelines and some 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)

Output:

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

def b():
    """
    This is
    not so lengthy
    docstring
    """
    print 'hmm...'

P.S: I have not tested it thoroughly yet, but this should get you started.

like image 77
Ashwini Chaudhary Avatar answered Nov 15 '22 01:11

Ashwini Chaudhary


Pyment allows to create, harmonize and convert docstrings.

It can't currently propose to expand raw description as \n, but it could be easy to add this functionality. You can open an issue to request it.

like image 31
daouzli Avatar answered Nov 15 '22 01:11

daouzli