[Python-Dev] Triple-quoted strings and indentation

Nick Coghlan ncoghlan at gmail.com
Mon Jul 11 11:07:46 CEST 2005

Reinhold Birkenfeld wrote:
> Guido van Rossum wrote:
>>On 7/5/05, Andrew Durdin <adurdin at gmail.com> wrote:
>>>I have written a patch that changes the way triple-quoted strings are
>>>scanned so that leading whitespace is ignored in much the same way
>>>that pep 257 handles it for docstrings. Largely this was for a
>>>learning experience in hacking the parser, but it would be very nice
>>>IMO if something of this sort could be implemented in a future version
>>>of Python.
>>I don't think so. It smells too much of DWIM, which is very unpythonic. EIBTI.
> Another idea, which is much more conservative: textwrap.dedent is highly under-
> rated and hidden. Why not make it builtin or a string method?
> Reinhold

Using Andrew's examples from the PEP:

         def usage(outfile):
              """Usage: %s [OPTIONS] <file> [ARGS]

                 --help                Display this help then exit.
                 --version             Output version information then exit.
                 """.dedent() % sys.argv[0])

             if 1:
                 import sys as _sys
                 _sys.path = %r
                 del _sys
                 \n""".dedent() % (sys.path,))

         class WrapTestCase(BaseTestCase):
             def test_subsequent_indent(self):
                 # Test subsequent_indent parameter
                  expect = '''\
                       * This paragraph will be filled, first
                         without any indentation, and then
                         with some (including a hanging
                 result = fill(self.text, 40,
                               initial_indent="  * ",
                               subsequent_indent="    ")
                 self.check(result, expect)

And if the loading of the textwrap module is deferred to the first call to 
dedent(), then it wouldn't even need to incur any extra start up overhead.

Although that last example is a bad one, since you end up testing textwrap 
against itself ;)


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-Dev mailing list