Python Programming/Source Documentation and Comments

< Python Programming

Documentation is the process of leaving information about your code. The two mechanisms for doing this in Python are comments and documentation strings.

Comments

There will always be a time in which you have to return to your code. Perhaps it is to fix a bug, or to add a new feature. Regardless, looking at your own code after six months is almost as bad as looking at someone else's code. What one needs is a means to leave reminders to yourself as to what you were doing.

For this purpose, you leave comments. Comments are little snippets of text embedded inside your code that are ignored by the Python interpreter. A comment is denoted by the hash character (#) and extends to the end of the line. For example:

#!/usr/bin/env python
# commentexample.py

# Display the knights that come after Scene 24
print("The Knights Who Say Ni!")
# print("I will never see the light of day!")

As you can see, you can also use comments to temporarily remove segments of your code, like the second print statement.

Comment Guidelines

The following guidelines are from PEP 8, written by Guido van Rossum.

Documentation Strings

But what if you just want to know how to use a function, class, or method? You could add comments before the function, but comments are inside the code, so you would have to pull up a text editor and view them that way. But you can't pull up comments from a C extension, so that is less than ideal. You could always write a separate text file with how to call the functions, but that would mean that you would have to remember to update that file. If only there was a mechanism for being able to embed the documentation and get at it easily...

Fortunately, Python has such a capability. Documentation strings (or docstrings) are used to create easily-accessible documentation. You can add a docstring to a function, class, or module by adding a string as the first indented statement. For example:

#!/usr/bin/env python
# docstringexample.py

"""Example of using documentation strings."""

class Knight:
    """
    An example class.
    
    Call spam to get bacon.
    """
    
    def spam(eggs="bacon"):
        """Prints the argument given."""
        print(eggs)

The convention is to use triple-quoted strings, because it makes it easier to add more documentation spanning multiple lines.

To access the documentation, you can use the help function inside a Python shell with the object you want help on, or you can use the pydoc command from your system's shell. If we were in the directory where docstringexample.py lives, one could enter pydoc docstringexample to get documentation on that module.

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.