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'
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.
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.
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.
just use print(input. doc)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With