Need cleanup advice for multiline string

David Bolen db3l.net at gmail.com
Wed Aug 12 18:04:45 CEST 2009


Robert Dailey <rcdailey at gmail.com> writes:

> Hey guys. Being a C++ programmer, I like to keep variable definitions
> close to the location in which they will be used. This improves
> readability in many ways. However, when I have a multi-line string
> definition at function level scope, things get tricky because of the
> indents. In this case indents are serving two purposes: For syntax and
> actual text output. The tabs for function scope should not be included
> in the contents of the string. (...)

Personally I'm in the camp that something like this should be hoisted
out of the code path (whether to global scope, a dedicated message
module or configuration file is a design choice).

But if it's going to stay inline, one approach that can maintain some
of the attractive qualities of a triple quoted string is to make use
of the textwrap module:

    import textwrap

    def RunCommand( commandList ):
       # ...
       if returnCode:
           failMsg = textwrap.dedent('''\
                     *************************************************
                     The following command returned exit code [{:#x}].
                     This represents failure of some form. Please review
                     the command output for more details on the issue.
                     ------------
                     {}
                     *************************************************
                     ''')

which removes any common leading whitespace (must be identical in terms
of any tabs/spaces).

This is still additional run-time processing, and most likely less
efficient than the joining of individual strings, but it does permit a
clean triple-quoted string so IMO is easier to read/maintain in the
source - providing the code indentation level doesn't get in the way
of the desired line length of the string.  You can also choose to
dedent the string a bit (say to the level of "failMsg") if needed
without being forced all the way back to the left margin.

You can also combine textwrap.dedent with some of the other options if
where the strings are defined makes it nicer if they still have some
indentation (say in a global Python module).  In that case, you'd most
likely just process them once when the module was imported, so any
inefficiency in textwrap.dedent is far less important.

-- David



More information about the Python-list mailing list