[Python-Dev] Re: Multiline string constants, include in the standard library?

Ville Vainio ville.vainio@swisslog.com
Mon, 29 Jul 2002 12:27:37 +0300


M.-A. Lemburg wrote:

> I think everybody has their own way of formatting multi-line
> strings and/or comments. There's no one-fits-all strategy.

Yep, but having a standard solution available to a one, very sensible 
strategy would be nice.

>
> So instead of trying to find a compromise, why don't you write up
> a flexible helper function for the new textwrap module ?

I don't think there is all that much implementation to do: 
inspect.getdoc() already has an implementation that seems to do the 
right thing, it's just that the stripping is embedded into the getdoc 
function, instead of having it available as a seperate function. 
textwrap might be a good place to put it, considering that the string 
module is going away - even if no actual wrapping takes place.

--------------------------------------------------
def getdoc(object):
    """Get the documentation string for an object.

    All tabs are expanded to spaces.  To clean up docstrings that are
    indented to line up with blocks of code, any whitespace than can be
    uniformly removed from the second line onwards is removed."""
    try:
        doc = object.__doc__
    except AttributeError:
        return None
    if not isinstance(doc, (str, unicode)):
        return None
    try:
        lines = string.split(string.expandtabs(doc), '\n')
    except UnicodeError:
        return None
    else:
        margin = None
        for line in lines[1:]:
            content = len(string.lstrip(line))
            if not content: continue
            indent = len(line) - content
            if margin is None: margin = indent
            else: margin = min(margin, indent)
        if margin is not None:
            for i in range(1, len(lines)): lines[i] = lines[i][margin:]
        return string.join(lines, '\n')
------------------------------------------