1

I have a question about docstrings in simple email python scripts.

message = """\
From: %s
To: %s
Subject: %s

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

I see docstrings like this often in email scripts. My question is, what is the docstring doing? I thought docstrings were used only for help commands and such. I apologize if this is a stupid question.

Thank you!

cs95
  • 274,032
  • 76
  • 480
  • 537
A. Mist
  • 25
  • 1
  • 5

3 Answers3

2

A string with """...""" (triple quotes) is called a multiline string. There is a distinction between a multiline string and a docstring. The latter is a subset of the former.

The one in question is being assigned to a variable, so it is not a docstring. A docstring is what you'd find at the top of a function, like this:

def foo():
    """This is a doc-string"""
    pass

And printing out foo.__doc__ gives you

print(foo.__doc__)
'This is a doc-string'

You should understand that only the first multiline string in a function (if it is un-assigned) becomes the docstring of a function (provided no optimisation switches are set) and the rest are all discarded.

In contrast,

message = """\
From: %s
To: %s
Subject: %s

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

Happens to be a multi-line string with some C-style format arguments that is assigned to the variable message.

Further reading:

cs95
  • 274,032
  • 76
  • 480
  • 537
1

That is not a docstring but just a normal string (str). Using the triple double-quotes ("""), or triple single-quotes ('''), you're telling to Python to use that as a long string. This string is separated by \n. Docstrings often uses this kind of long string to ease the read.

In your code, seems like it's preparing the email, using variables to specify the subject, text, CC, etc.

Hope it makes sense.

joegalaxian
  • 320
  • 1
  • 7
0

It's because it's useful to write the string in multiple lines, from the docs:

String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''.

Vinícius Figueiredo
  • 5,430
  • 3
  • 18
  • 37