The last section’s example includes a docstring for its module, but remember that docstrings can be used for class components as well. Docstrings, which we covered in detail in Chapter 15, are string literals that show up at the top of various structures and are automatically saved by Python in the corresponding objects’ __doc__ attributes. This works for module files, function defs, and classes and methods.
Now that we know more about classes and methods, the following file, docstr.py, provides a quick but comprehensive example that summarizes the places where docstrings can show up in your code. All of these can be triple-quoted blocks or simpler one-liner literals like those here:
"I am: docstr.__doc__"
def func(args):
"I am: docstr.func.__doc__"
pass
class spam:
"I am: spam.__doc__ or docstr.spam.__doc__ or self.__doc__"
def method(self):
"I am: spam.method.__doc__ or self.method.__doc__"
print(self.__doc__)
print(self.method.__doc__)
The main advantage of documentation strings is that they stick around at runtime. Thus, if it’s been coded as a docstring, you can qualify an object with its __doc__ attribute to fetch its documentation (printing the result interprets line breaks if it’s a multiline string):
>>>import docstr>>>docstr.__doc__'I am: docstr.__doc__' >>>docstr.func.__doc__'I am: docstr.func.__doc__' >>>docstr.spam.__doc__'I am: spam.__doc__ or docstr.spam.__doc__ or self.__doc__' >>>docstr.spam.method.__doc__'I am: spam.method.__doc__ or self.method.__doc__' >>>x = docstr.spam()>>>x.method()I am: spam.__doc__ or docstr.spam.__doc__ or self.__doc__ I am: spam.method.__doc__ or self.method.__doc__
A discussion of the PyDoc tool, which knows how to format all these strings in reports and web pages, appears in Chapter 15. Here it is running its help function on our code under Python 2.X (Python 3.X shows additional attributes inherited from the implied object superclass in the new-style class model—run this on your own to see the 3.X extras, and watch for more about this difference in Chapter 32):
>>> help(docstr)
Help on module docstr:
NAME
docstr - I am: docstr.__doc__
FILE
c:\code\docstr.py
CLASSES
spam
class spam
| I am: spam.__doc__ or docstr.spam.__doc__ or self.__doc__
|
| Methods defined here:
|
| method(self)
| I am: spam.method.__doc__ or self.method.__doc__
FUNCTIONS
func(args)
I am: docstr.func.__doc__
Documentation strings are available at runtime, but they are less flexible syntactically than # comments, which can appear anywhere in a program. Both forms are useful tools, and any program documentation is good (as long as it’s accurate, of course!). As stated before, the Python “best practice” rule of thumb is to use docstrings for functional documentation (what your objects do) and hash-mark comments for more micro-level documentation (how arcane bits of code work).