• About
  • Archive
  • RSS

code.dump();

Handling Python Docstring Indentation

def trim(docstring):
    if not docstring:
        return ''
    lines = docstring.expandtabs().splitlines()

    # Determine minimum indentation (first line doesn't count):
    indent = sys.maxint
    for line in lines[1:]:
        stripped = line.lstrip()
        if stripped:
            indent = min(indent, len(line) - len(stripped))

    # Remove indentation (first line is special):
    trimmed = [lines[0].strip()]
    if indent < sys.maxint:
        for line in lines[1:]:
            trimmed.append(line[indent:].rstrip())

    # Strip off trailing and leading blank lines:
    while trimmed and not trimmed[-1]:
        trimmed.pop()
    while trimmed and not trimmed[0]:
        trimmed.pop(0)
    return '\n'.join(trimmed)

With this algorithm, an indented documentation string such as this…

def foo():
    """
    A multi-line
    docstring.
    """

…is converted to: "A multi-line\ndocstring."

  • Posted by inky
  • Tags:
    • python
  • April 10, 2009, 3:05am

  • Permalink
← Previous Post   Next Post →

About

A place for code snippets, keyboard shortcuts, dirty hacks and other fun tricks. Use at your own risk!

Members

  • inky
  • arood
  • beret
  • nosmo

Search

Colophon

A group tumblelog, originally by inky. Powered by Tumblr and themed by Bill Israel.