What is the use of a docstring in this python code?

622 views Asked by At

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!

3

There are 3 answers

0
Vinícius Figueiredo On

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 '''...'''.

1
this be Shiva On

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:

0
joegalaxian On

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.