Docstrings

Learn about documenting your code.

A brief introduction to docstrings

Having a good coding style is important. One of the key aspects of a good coding style is documenting our work through the liberal use of comments. Comments help the reader of the code understand what the code is doing without having to dive into code statements and figure out the logic. Earlier we encountered a special kind of comment called a docstring. We’ll examine docstrings in some more detail in this lesson.

A docstring is a comment in a code file that documents the working of a certain section of the code. Unlike regular comments, docstrings need to be the first lines in a file or in the definition of a function, class, or method. Docstrings exist in several languages, including Python. In Python the docstring becomes a part of the enclosing object as part of its __doc__ attribute. Regular comments, on the other hand, are stripped out by the Python interpreter when converting code to bytecode and aren’t present in the object’s attributes.

Docstrings are enclosed in triple double quotes (""") or triple single quotes ('''). If the first comment line in a function isn’t enclosed in one of these delimiters and instead uses the # character, it’s considered a regular comment and not a docstring.

Docstrings can be just a single line, as shown below.

Get hands-on with 1200+ tech skills courses.