Python Syntax and Semantics - Comments and Docstrings

Comments and Docstrings

Python has two ways to annotate Python code. One is by using comments to indicate what some part of the code does. Single-line comments begin with the hash character ("#") and are terminated by the end of line. Comments spanning more than one line are achieved by inserting a multi-line string (with """ as the delimiter one each end) that is not used in assignment or otherwise evaluated, but sits in between other statements.

Commenting a piece of code:

def getline: return sys.stdin.readline # Get one line and return it

Commenting a piece of code with multiple lines:

def getline: return sys.stdin.readline """this function gets one line and returns it"""

Docstrings (documentation string), that is, strings that is located alone without assignment as the first indented line within a module, class, method or function automatically set their contents as an attribute named __doc__, which is intended to store a human-readable description of the object's purpose, behavior, and usage. The built-in help function generates its output based on __doc__ attributes. Such strings can be delimited with " or ' for single line strings, or may span multiple lines if delimited with either """ or ''' which is Python's notation for specifying multi-line strings. However, the style guide for the language specifies that triple double quotes (""") are preferred for both single and multi-line docstrings.

Single line docstring:

def getline: """Get one line from stdin and return it.""" return sys.stdin.readline

Multi-line docstring:

def getline: """Get one line from stdin and return it.""" return sys.stdin.readline

Docstrings can be as large as the programmer wants and contain line breaks. In contrast with comments, docstrings are themselves Python objects and are part of the interpreted code that Python runs. That means that a running program can retrieve its own docstrings and manipulate that information. But the normal usage is to give other programmers information about how to invoke the object being documented in the docstring.

There are tools available that can extract the docstrings to generate an API documentation from the code. Docstring documentation can also be accessed from the interpreter with the help function, or from the shell with the pydoc command pydoc.

The doctest standard module uses interactions copied from Python shell sessions into docstrings, to create tests.

Read more about this topic:  Python Syntax And Semantics

Famous quotes containing the word comments:

    My note to you I certainly did not expect to see in print; yet I have not been much shocked by the newspaper comments upon it. Those comments constitute a fair specimen of what has occurred to me through life. I have endured a great deal of ridicule without much malice; and have received a great deal of kindness, not quite free from ridicule. I am used to it.
    Abraham Lincoln (1809–1865)