What is a Docstring?
Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods.
An object’s docsting is defined by including a string constant as the first statement in the object’s definition. It’s specified in source code that is used, like a comment, to document a specific segment of code.
Unlike conventional source code comments the docstring should describe what the function does, not how.
All functions should have a docstring This allows the program to inspect these comments at run time, for instance as an interactive help system, or as metadata.
Docstrings can be accessed by the __doc__ attribute on objects.
How should a Docstring look like?
The doc string line should begin with a capital letter and end with a period. The first line should be a short description.
Don’t write the name of the object. If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description.
The following lines should be one or more paragraphs describing the object’s calling conventions, its side effects, etc.
Let’s show how an example of a multi-line docstring:
def my_function(): """Do nothing, but document it. No, really, it doesn't do anything. """ pass
Let’s see how this would look like when we print it
>>> print my_function.__doc__ Do nothing, but document it. No, really, it doesn't do anything.
Declaration of docstrings
The following Python file shows the declaration of docstrings within a python source file:
""" Assuming this is file mymodule.py, then this string, being the first statement in the file, will become the "mymodule" module's docstring when the file is imported. """ class MyClass(object): """The class's docstring""" def my_method(self): """The method's docstring""" def my_function(): """The function's docstring"""
How to access the Docstring
The following is an interactive session showing how the docstrings may be accessed
>>> import mymodule >>> help(mymodule)
Assuming this is file mymodule.py then this string, being the first statement in the file will become the mymodule modules docstring when the file is imported.
>>> help(mymodule.MyClass) The class's docstring >>> help(mymodule.MyClass.my_method) The method's docstring >>> help(mymodule.my_function) The function's docstring
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.