Docstrings are a triple quoted string that you declare at the beginning of object definitions such as functions, classes, and class methods. They are used to describe the purpose of the function, as a brief summary, but not describe how the function works. To describe how a function works, you would use regular comments.
A good Python coding habit is to include a docstring for every function, method or class object you write. Docstring conventions are outlined in PEP 257.
There are two ways that users can view your function’s docstrings, which illustrate why they are so useful.
- The user can type
help(function_name)
in the console orĀprint(help(function_name))
in an IDE and they will see the docstring listed under the function name as a handy summary of what the function does. For example:>>> help(docstring_test) Help on function docstring_test in module __main__: docstring_test() This is the docstring in triple quotes, right below the function definition line.
- The user can type
function_name.__doc__
For example:>>> docstring_test.__doc__ 'This is the docstring in triple quotes, right below the function definition line.'
Here is a full code example:
def docstring_test(): """This is the docstring in triple quotes, right below the function definition line.""" print("This is how you access a docstring: \nfunction_name.__doc__") print(docstring_test.__doc__) docstring_test()
Which yields:
This is how you access a docstring: function_name.__doc__ This is the docstring in triple quotes, right below the function definition line.
For more information, see:
https://en.wikipedia.org/wiki/Docstring
https://docs.python.org/2/tutorial/controlflow.html#tut-docstrings