Multi-line docstrings
Duncan Booth
duncan.booth at invalid.invalid
Sat Dec 23 07:19:48 EST 2006
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. If you
are just printing __doc__ in interactive mode then live with the extra
whitespace. If you are printing out lots of docstrings as part of some
documentation tool then use textwrap.dedent to remove the common leading
spaces.
>
> Another possibility is to use implicit concatenation of string
> literals, e.g.
>
<snip>
> This includes no spurious whitespace, or even any newlines; if you
> want these, you must put them explicitly in the string:
<snip>
... which is why the triple-quoted format is recommended. BTW, you missed
this way of doing it which ensures that all lines, even the first one have
the same indentation (and therefore textwrap.dedent will strip it quite
nicely):
def Meet(Alice, Bob) :
'''\
arranges a meeting between Alice and Bob.
Returns a reference to the meeting booking object.
'''
and if you want to do string concatenation you can always get rid of those
pesky backslashes:
def Meet(Alice, Bob) :
("arranges a meeting between Alice and Bob.\n"
"Returns a reference to the meeting booking object.")
More information about the Python-list
mailing list