How does help() indent doc strings?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Feb 3 18:54:10 EST 2013


Roy Smith wrote:

> It would be much nicer to be able to do:
> 
>     epilog = """This my very long epilog string
>                 which goes on for several lines.
>                 """
> 
> and have dedent() figure out the indenting like help() does for
> docstrings.  How can I do that (in python 2.7)?

The Source is strong^W tricky in this one... 

The site module adds the help() function to the builtins:

http://hg.python.org/cpython/file/2.7/Lib/site.py

The help() function in turn calls pydoc to do the actual work:

http://docs.python.org/2/library/pydoc.html

The source is rather large and not the easiest to read, but if you read it
you will see it does not use textwrap.dedent anywhere.

http://hg.python.org/cpython/file/2.7/Lib/pydoc.py

You're welcome to read it and decipher how it formats text if you like. But
possibly the easiest way to get the effect you are after is with a small
helper function:

def prepare(text):
    spaces = (' ', '\t')
    if text and not text.startswith(spaces):
        # Find the indent of the *second* non-blank line.
        indent = []
        lines = text.splitlines()
        for linenum, line in enumerate(lines[1:], 1):
            line.rstrip()
            if line.startswith(spaces):
                for c in line:
                    if c in spaces: indent.append(c)
                    else: break
                break
        lines[0] = ''.join(indent) + lines[0]
        text = '\n'.join(lines)
    return text



And in use:

py> epilogue = """This my very long epilogue string
...     which goes on for several lines.
...     Like this.
...     """
py>
py> print textwrap.dedent(epilogue)
This my very long epilogue string
        which goes on for several lines.
        Like this.

py> print textwrap.dedent(prepare(epilogue))
This my very long epilogue string
which goes on for several lines.
Like this.





-- 
Steven




More information about the Python-list mailing list