Multi-line docstrings

Lawrence D'Oliveiro ldo at geek-central.gen.new_zealand
Sun Dec 24 18:37:20 EST 2006


In message <Xns98A2771E69D6Eduncanbooth at 127.0.0.1>, Duncan Booth wrote:

> Lawrence D'Oliveiro <ldo at geek-central.gen.new_zealand> wrote:
> 
>> The Python docs recommend the use of triple-quoted string literals for
>> docstrings, e.g.
>> 
>>     def Meet(Alice, Bob) :
>>         """arranges a meeting between Alice and Bob.
>>         Returns a reference to the meeting booking object."""
>>         ...
>>     #end Meet
>> However, these tend to get messed up by indentation whitespace, which
>> gets spuriously included as part of the string.
> 
> Not spuriously included: included by design, but sometimes annoying.

The problem is that the treatment of indentation whitespace in triple-quoted
strings is at odds with its use for syntax purposes elsewhere in the
language.

Instead of preserving all included whitespace, a better rule for
triple-quoted strings might be to strip whitespace up to the current
indentation level from each continuation line. That is, each line _must_
begin with at least that amount of whitespace, otherwise it's an error; any
extra whitespace is preserved. E.g.

    a = """two lines
      of text"""

being equivalent to

    a = "two lines\n  of text"

Or, a simpler rule might be to strip _all_ whitespace at the start of each
continuation line, regardless of indentation level. So the triple-quoted
example above becomes equivalent to

    a = "two lines\nof text"

If you _want_ to include some whitespace at the start of a continuation
line, simply precede it by something that isn't literal whitespace:

    a = """two lines
     \x20 of text"""

becomes equivalent to

    a = "two lines\n  of text"

(It might be nice if "\ " was recognized as equivalent to "\x20" for this
purpose.)



More information about the Python-list mailing list